Reputation: 53
I'm new with gdb and I don't understand the values given to the output. I've been testing some toy program just to learn the behaviour.
#include <stdbool.h>
#include <stdio.h>
int main(){
bool arr[2] = {true, false};
printf("Value at index 2 of array is %d\n", arr[2]);
return 0;
}
As we can observe, the trick at the buggy program is in arr[2]
where we can expect some NULL
. But when I compile it gives:
$ ./a.exe
Value at index 2 of array is 130
However with gdb the behaviour looks pretty different:
$ gdb a.exe
(gdb) b main
(gdb) run
Thread 1 "a" hit Breakpoint 1, main () at table.c:5
5 bool arr[2] = {true, false};
(gdb) p arr
$1 = {34, false}
(gdb) p arr[2]
$2 = 211
Where is the returned value of 130 given by a.exe
? Why 130? Why 211? And I absolutely didn't understand $1 = {34, false}
. I've compiled with -g
flag. It means: gcc -g buggy.c
My gcc version compiler gives this: gcc (GCC) 9.3.0
GDB Version: GNU gdb (GDB) (Cygwin 9.2-1) 9.2
My OS runs: Windows 7 Professional i686
Working on: Cygwin setup version 2.905 (32 bit)
Upvotes: 1
Views: 871
Reputation: 23802
arr
only has 2 elements, accessing arr[2]
amounts to accessing the third element of the array, wich does not exist, this invokes undefined behavior, as a consequence, no consistent behavior is to be expected from this program.
- undefined behavior
Behavior, upon use of a nonportable or erroneous program construct or of erroneous data,for which this International Standard imposes no requirements.
- NOTE
Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).
$1 = {34, false}
is the likely result of you printing the array before it's initialized, setting the breakpoint in the next line should give you the correct results.
Upvotes: 4
Reputation: 30035
C++ doesn't have any array bound checks in the language (1), so if you index off the end of an array you'll get undefined behavior which means the compiler is free to do whatever it finds convenient.
In practice this means it will access whatever memory would have been used if the array had been bigger, running one past the allocated memory for the array into memory that's already used for something else.
You've not set any value into that memory in your program so it will return whatever value just happens to be in that memory.
When you run under a debugger you move things around in memory and the computer runs things a little differently so there is no reason to expect that the value will be the same as a normal run. It may differ every time you run the program anyway!
(1) some library functions such as vector::at
have bounds checks and some compilers offer it as an extension but the core language doesn't define any.
Upvotes: 1