Result even after crossing the limit of the initialized array in C++ - c++

After initialization of an array up to certain limit and then printing the array out of that limit it is still printing the result.Why ?
Example :
#include <iostream>
using namespace std;
int main() {
int A[2] = {};
cout << A[0] << "\n";
cout << A[1] << "\n";
cout << A[2] << "\n";
cout << A[3] << "\n";
cout << A[4] << "\n";
return 0;
}
The Output is:
0
0
0
0
-13120
Here I have just initialized the array till 2 places. But still I am getting the result of A[2],A[3] and so on.

Crossing the limit results in undefined behavior (UB). It can print and looks like working normally, it could crash, it could stuck,or it could be anything.
So, you should not rely on it if it works sometimes.

Exceeding an array's bounds is undefined behaviour. This means that the program may do simply nothing, may print something, may exit the program, may ... behaviour is simply not defined.
So printing out something is still one possible behaviour, but you must not rely on this behaviour.

Related

int() causing overwrite of argument

This is probably something fairly simple I'm missing, but could someone explain what's going on with my code here?
I'd expect arrayone[0] to be unchanged, as I'm never reassigning to it, but somewhere, it's being changed from 3 to 1.
int arrayone[1];
int arraytwo[1];
arrayone[0]=3;
cout << "expected: 3\n";
cout << arrayone[0] << "\n";
arraytwo[0] = int(arrayone[0]/4.0); //int (5/4) = 0
cout << "expected: 3 0\n";
cout << arrayone[0] << " " << arraytwo[0] << "\n";
arraytwo[1] = int(arrayone[0]/2.0); //int (3/2) = 1
cout << "expected: 3 0 1\n";
cout << arrayone[0] << " " << arraytwo[0] << " " << arraytwo[1] <<"\n";
(that final line is returning 1 0 1 instead of 3 0 1)
I've tried testing a few things, looking at where it gets changed; and I think it has to do with the int() function, but I don't understand why.
You use arraytwo[1], which is out of bounds. Because of that you will have undefined behavior.
Perhaps you meant to define arraytwo as an array of two elements:
int arraytwo[2];
The casting you do with int() have nothing to do with it.
On a note related to the casting: If you want an integer after the division, why not do integer division to start with? As in
arraytwo[0] = arrayone[0] / 4;
You need to declare arraytwo with a size of two, i.e., elements 0 and 1, like this
int arraytwo[2];
You don't say what toolchain you are using, but this is the sort of thing that both static and dynamic analysis will detect (for example clang static analyzer and sanitizer respectively).
arraytwo[1] = int(arrayone[0]/2.0); //int (3/2) = 1
Here you are writing to an area beyond arraytwo (it has size 1, so you can only write to arraytwo[0]). That's undefined behavior - what happens in practice is that it's writing to the calculated position anyway, and that's the memory where arrayone is (at least on your setup, it depends on the machine, the compiler used and many settings). This is called memory corruption, and depending on the magnitude of the error you could even get a stack corruption, or, of course, a segmentation fault.
To prevent such mistakes, most compilers will issue a warning on this line. If this isn't happening for you, try looking into whether you can configure your compiler to be more strict with warnings.

C/C++ the result of the uninitialized array

It might be a boring question! thanks!
Here's the code:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int a[5] = {0};
int b[5];
cout << a << endl;
cout << b << endl;
for (int i = 0; i < 5; i++)
{
cout << a[i] << " ";
}
cout << endl;
for (int i = 0; i < 5; i++)
{
cout << b[i] << " ";
}
cout << endl;
return 0;
}
in Ubuntu: g++ a.cpp
In windows with DEV C++ ,MinGW GCC 4.7.2:
So the question is focused on the array b:
I know I haven't initialized the array b.
Array b is full of garbage values, but why there is always having '0' with the fixed position like "X 0 X 0 X"??
What happens inside??
Just a protection mechanism?
That is undefined behavior. There is no guarantee, if these zeros are there, that just accidentally is true.
The explanation is, that for some random reason at these places in memory a 0 was stored before it was reused for your purpose here. Since you allocate your arrays on the stack, these zeroes are probably from a prior function call and might be some padding. The compiler will do that as he pleases.
The behaviour on reading uninitialised elements of an array is undefined. The compiler is allowed to do anything.
(All the elements of a can be read due to the brace initialisation, although in C++ you can write int a[5] = {};).

Why int ia2[10] has a default value of 0 even though it is defined inside a function?

I'm new to C++ and is trying to learn the concept of arrays. I saw the code and statement below from C++ primer.
As with variables of built-in type, a default-initialized array of
built-in type that is defined inside a function will have undefined
values.
Judging from this statement, the int ia2[10] below is define inside the int main(){} function and therefore should not have default value and all its elements should be undefined. However, when I tried to print out their value, they are all equal to 0, which is the default value for any uninitialised int array.
Why is this happening?
int main() {
string sa2[10]; //all elements are empty strings
int ia2[10]; //all elements are undefined
for (int i = 0; i < 10; i++){
cout << "sa2[" << i << "] " << sa2[i] << endl;
cout << "ia2[" << i << "] " << ia2[i] << endl;
}
}
Output:
sa2[0]
ia2[0] 0
sa2[1]
ia2[1] 0
sa2[2]
ia2[2] 0
sa2[3]
ia2[3] 0
sa2[4]
ia2[4] 0
sa2[5]
ia2[5] 0
sa2[6]
ia2[6] 0
sa2[7]
ia2[7] 0
sa2[8]
ia2[8] 0
sa2[9]
ia2[9] 0
It isn't forced to have some random value. It's undefined what value will be there, so it could be anything, including all zeroed out. Also note that reading the value is undefined behavior.

Integer not comparing equal to its value

I've got a piece of code I am trying to debug, which is producing bizarre results. An integer, which very clearly contains the value six, compares false to the literal 6.
In my code, this code:
int allGreen = 0;
int index = 0;
while (ch->fb[index]->selection_color() == FL_GREEN)
{
++allGreen;
++index;
}
std::cout << allGreen << std::endl;
std::cout << std::boolalpha << (allGreen == 6) << std::endl;
Produces the output:
6
false
I am compiling with g++ 4.8.2 on Ubuntu.
How can this possibly happen?
Edit: Removing all green from the condition doesn't help.
Edit 2: index and allGreen are equal, as expected. Neither is equal to 6, despite both being 6.
What is the size of ch->fb array? If it is 6 or less, it could be compiler optimizing undefined behavior here.
When seeing some simple loop like
while ( a[i] ) i++;
Compiler can make an assumption that i never goes outside of a array, otherwise program invokes undefined behavior. That is i lies between 0 and size of a - 1.
Later, if compiler sees something like i == 8, there 8 is larger than size of a - 1, it replaces this condition with false.
Just to be sure, you can look at assembly code.
The literal '6' is not an integer and does not have a value of 6.
As deniss already pointed out, accessing an array out of bounds is undefined behaviour, so maybe that's the cause. Make sure to check for the array's bounds, too.
So if it's OK to count every selection_color of the array, you could try:
const int MAX_FB_VALUES = 6;
// ...
int countOfGreen = 0;
for (int i = 0; i < MAX_FB_VALUES; ++i)
{
if(ch->fb[i]->selection_color() == FL_GREEN)
++countOfGreen;
}
std::cout << countOfGreen << std::endl;
std::cout << std::boolalpha << (countOfGreen == MAX_FB_VALUES) << std::endl;
Although it would be better to use a container anyway, of course.

c++ strange std::cout behaviour using pointers [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the correct answer for cout << c++ << c;?
I just ouputted text, when I suddenly noticed.
#include <iostream>
int main()
{
int array[] = {1,2,3,4};
int *p = array;
std::cout << *p << "___" << *(p++) << "\n";
// output is 1__1. Strange, but I used brackets! it should be at
// first incremented, not clear.
p = array;
std::cout << *p << "___" << *(++p) << "\n";
// output is 2_2 fine, why first number was affected? I didn't intend
// to increment it, but it was incremented
p=array;
std::cout << *p << "___" << *(p + 1) << "\n";
// output is 1_2 - as it was expected
p = array;
return 0;
}
Such behaviour is strange for me, why is it so?
You are causing undefined behaviour, so anything can happen and there's no point in speculating about why.
The expression
std::cout<<*p<<"___"<<*(p++)<<"\n"
Is one example: the order of evaluation of all the things between << is unspecified, so *p and *(p++) are unsequenced with respect to each other (i.e. the compiler is not required do do either one first). You are not allowed to modify a variable and then use it without the modification and usage being sequenced, and so this causes undefined behaviour.
The same thing applies to all the other places in that program where a variable is modified and used unsequenced separately in the same expression.