See the following code snippet:
int len = -2;
char* buff = (char*) malloc(len+4);
if (len > sizeof(buff))
puts("ERROR!");
else
puts("OK!");
Compiling and running this code on Ubuntu-14.04 (64-bit) using GCC 4.8.2 prints ERROR
.
I used the following code to print the values of len
and sizeof(buf)
:
printf("len = %d, size = %lu", len, sizeof(buff));
and it prints:
len = -2, size = 8
Changing the value of len
has no effect on the value of sizeof(buff)
, not even for a positive len
.
If I'm not mistaken, the value 8
is the length of a pointer address on my 64-bit machine, which is constant no matter what I give to malloc
. If this is it, I have two questions:
1) Why is the above if
statement printing ERROR
? (Since -2 is not greater than 8 !!)
2) Why doesn't the following code print 8
?
char array[10];
printf("%lu", sizeof(array));
This code prints the length of the array. What's the difference between a char[]
and char*
from malloc
? I know that the first is allocated on the stack, and the latter is dynamically allocated on heap, but in any case they are both pointer addresses of the system memory. I don't understand the different behavior of sizeof
relative to a char[]
and char*
from malloc
! It seems inconsistent!