char *cp = (char *) malloc(1);
strcpy(cp, "123456789");
puts(cp);
output is "123456789" on both gcc (Linux) and Visual C++ Express, does that mean when there is free memory, I can actually use more than what I've allocated with malloc()
?
and why malloc(0)
doesn't cause runtime error?
Thanks.
It could be that you're in Debug mode, where a call to malloc will actually call _malloc_dbg. The debug version will allocate more space than you have requested to cope with buffer overflows. I guess that if you ran this in Release mode you might (hopefully) get a crash instead.
No. It means that your program behaves badly. It writes to a memory location that it does not own.
You may be allowed to use until the memory reaches some program memory or other point at which your applicaiton will most likely crash for accessing protected memory
When you ask
malloc
for 1 byte, it will probably get 1 page (typically 4KB) from the operating system. This page will be allocated to the calling process so as long as you don't go out of the page boundary, you won't have any problems.Note, however, that it is definitely undefined behavior!
Consider the following (hypothetical) example of what might happen when using
malloc
:malloc(1)
malloc
is internally out of memory, it will ask the operating system some more. It will typically receive a page. Say it's 4KB in size with addresses starting at 0x1000malloc(1)
malloc
still has some memory left so it doesn't need to ask the operating system for more. It will probably return the address 0x1001.malloc
, you will get into troubles when you use the address from the secondmalloc
because you will overwrite the data.So the point is you definitely get 1 byte from malloc but it might be that
malloc
internally has more memory allocated to you process.