Lets say i did somthing like this:
char* m = (char*)malloc(sizeof(char) * 100);
m = (char*)realloc(m, 0)
what will happen to m? and will the memory be released? Thanks
CodePudding user response:
In this case the behavior is implementation defined.
From the C Standard (7.22.3 Memory management functions)
- ... If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned to indicate an error, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.
For example the system can free the allocated memory and return a non-null pointer.
CodePudding user response:
what will happen to m? and will the memory be released?
C is evolving in this area.
C17 updated this spec.
"If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned to indicate an error, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.".
C17dr 7.22.3
And has
Invoking
realloc
with a size argument equal to zero is an obsolescent feature.
C17dr 7.31.12 2
Best to avoid realloc(m, 0)
and call free(m); m = NULL;
to free the allocation.
m = (char*)realloc(m, 0)
may not completely free memory resources and return non-NULL
.