free, realloc und Nullpointer
-
Hi an Alle,
ich hab letztens beim durchblättern der Manpages gelesen, dass ein Aufruf, der Funktione "free", auf einen Nullpointer (also auf die Addresse 0x0), keinen Effekt hat. Das gleiche soll mit realloc funktionieren, so dass ein simples malloc daraus wird. Meine Frage ist, ob das verhalten auf allen System zu finden ist, oder ob das Linux spezifisch ist. Also läuft forlgender code, ohne Absturz, auf allen ANSI C kompatieblen Compielern?#include <stdio.h> #include <stdlib.h> int main( int argc, char* argv[] ) { free( NULL ); return 0; }
-
jo
-
Gut zu wissen.
Danke!
-
Standard schrieb:
7.20.3.2 The free function
Synopsis
1 #include <stdlib.h>
void free(void *ptr);
Description
2 The free function causes the space pointed to by ptr to be deallocated, that is, made
available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if
the argument does not match a pointer earlier returned by the calloc, malloc, or
realloc function, or if the space has been deallocated by a call to free or realloc,
the behavior is undefined.
Returns
3 The free function returns no value.
7.20.3.3 The malloc function
Synopsis
1 #include <stdlib.h>
void *malloc(size_t size);
Description
2 The malloc function allocates space for an object whose size is specified by size and
whose value is indeterminate.
Returns
3 The malloc function returns either a null pointer or a pointer to the allocated space.
7.20.3.4 The realloc function
Synopsis
1 #include <stdlib.h>
void *realloc(void *ptr, size_t size);
Description
2 The realloc function deallocates the old object pointed to by ptr and returns a
pointer to a new object that has the size specified by size. The contents of the new
object shall be the same as that of the old object prior to deallocation, up to the lesser of
the new and old sizes. Any bytes in the new object beyond the size of the old object have
indeterminate values.
3 Ifptr is a null pointer, the realloc function behaves like the malloc function for the
specified size. Otherwise, if ptr does not match a pointer earlier returned by the
calloc, malloc, or realloc function, or if the space has been deallocated by a call
to the free or realloc function, the behavior is undefined. If memory for the new
object cannot be allocated, the old object is not deallocated and its value is unchanged.
Returns
4 The realloc function returns a pointer to the new object (which may have the same
value as a pointer to the old object), or a null pointer if the new object could not be
allocated.