int *ptr = malloc(sizeof(char));
*ptr = 100000;
printf("%d\n", *ptr); // 100000
Shouldn’t that only allocate enough memory for a char, i.e. 1 byte? Therefore shouldn’t the largest number be 255?
How does it still print 100000?
Update
Thanks for the answers. If it overwrites the next bytes, how does C then know that this number is larger than one byte, and not just look in the first byte?
Because C has no range-checking of memory. It allocates a byte, and then your assignment via the pointer overwrites it and the next three bytes. If you had allocated another bit of memory right after the first
malloc, but before the assignment, you might have overwritten part of the heap (depending on how your malloc works).This is why pointers can be very dangerous in C.
The
%din the format statement (plus the type of the variable) tells the compiler you are looking at anint, and accesses all four bytes.Note that if you really had assigned the value to a char, e.g.
char *ptr; *ptr = 100000;then with some compilers (and assuming plain
charis treated as signed but default) it would have printed out -96, not 255 (or 127). This is because the compiler doesn’t automatically limit the value to the highest value that can fit (127 in a signed char, 255 in an unsigned char), but instead it just overflows. Most compilers will complain that you are trying to assign a constant value that overflows the variable.The reason it is -96, is that 100000 % 256 is 160, but as a signed char it is output as -(256-160).