I am writing an application in c in which I’m allocating the memory needed for some arrays dynamically. I know that many of those arrays will need zero allocation. So, will there be a problem when I call free on them? egfree(malloc(0 * sizeof(int)));? I know my application compiles and runs ok on my machine, but can I rely on this? Cheers!
I am writing an application in c in which I’m allocating the memory needed
Share
malloc(0)may (this is implementation-defined) return a null pointer, or may return a new pointer each time you call it. In either case, the return value is valid to pass tofree, sincefree(0)is a no-op anyway. However, due to some nasty issues with detecting and handling failure ofreallocand disagreements between ISO C and POSIX, I would strongly advise you never to pass size 0 tomallocorrealloc. You can always simply add+1or|1to the end of the argument tomalloc, and then you’re certain to get a unique pointer (different from the null pointer or the address of any other object) every time you call it.Another reason not to use
malloc(0)is that you have to always check the return value ofmallocto detect failure, whereasmalloc(0)can return a null pointer on success. This makes all of your error checking code more complicated since you have to special-case the non-error case where the size argument was 0.