简体   繁体   中英

I used malloc(0) for a pointer to char, and my code works. Why is that?

I created an array of pointers to char . I used malloc(0) to allocate memory for those pointers.

After that, I used scanf() to enter exactly one word to the bytes allocated by malloc(0 and it worked.

Why is that?

First of all, from the man page for malloc() , ( emphasis mine )

If size is 0, then malloc() returns either NULL , or a unique pointer value that can later be successfully passed to free() .

So, it's not guaranteed that malloc(0) will return NULL, always. So, your NULL check may not be a success.

Then, to answer

Why is that?

because, in case malloc(0) returns a pointer other han NULL, it is only fit to be used as an argument to a later call to free() , nothing else. In your case, you're trying to write into the memory. Doing so is essentially attempt to write into an invalid memory , a memory which not allocated to your program. This invokes undefined behavior .

The real beauty of UB is that, sometimes, program invoking UB appear to work just fine .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM