I’m a bit confused about malloc() function.
if sizeof(char) is 1 byte and the malloc() function accepts N bytes in argument to allocate, then if I do:
char* buffer = malloc(3);
I allocate a buffer that can to store 3 characters, right?
char* s = malloc(3);
int i = 0;
while(i < 1024) { s[i] = 'b'; i++; }
s[i++] = '$';
s[i] = '\0';
printf("%s\n",s);
it works fine. and stores 1024 b's in s.
bbbb[...]$
why doesn’t the code above cause a buffer overflow? Can anyone explain?
malloc(size)returns a location in memory where at leastsizebytes are available for you to use. You are likely to be able to write to the bytes immediately afters[size], but:malloc()has used to keep track of what your program has used. Corrupting this is very bad!s[size + large_number]It’s difficult to say which one of these will happen because accessing outside the space you asked
malloc()for will result in undefined behaviour.In your example, you are overflowing the buffer, but not in a way that causes an immediate crash. Keep in mind that C does no bounds checking on array/pointer accesses.
Also,
malloc()creates memory on the heap, but buffer overflows are usually about memory on the stack. If you want to create one as an exercise, useinstead. This will create an array of 3 chars on the stack. On most systems, there won’t be any free space after the array, and so the space after
s[2]will belong to the stack. Writing to that space can overwrite other variables on the stack, and ultimately cause segmentation faults by (say) overwriting the current stack frame’s return pointer.One other thing:
sizeof(char)is actually defined by the standard to always be 1 byte. However, the size of that 1 byte might not be 8 bits on exotic systems. Of course, most of the time you don’t have to worry about this.