dynamic Memory allocation and free in C
Lets say i have created a string dynamically in the program
char* s = malloc(sizeof(char) * 128);
before we start using s, How to check whether the memory is allocated or not?开发者_StackOverflow
free(s);
And before using free() , I want to check are there any other pointers pointing to s .
malloc()
returns a pointer to the newly allocated memory or NULL.
So check for NULL
char *s = malloc(128); /* sizeof (char), by definition, is 1 */
if (s == NULL) {
/* no memory allocated */
} else {
/* use memory */
free(s);
}
There are other pointers pointing to where s
points only if you (the programmer) created them.
And before using free() , I want to check are there any other pointers pointing to s .
In general you can't do that - you have to manage what all the other pointers are doing yourself.
One common helper is to set 's' to NULL after freeing it, then you can at least detect if 's' is still in use in your other functions, but you can't automatically check for any copies of 's'.
The specification of malloc
says that it will return NULL
on fail. So if malloc
does not return NULL
then you can depend on the compiler that the memory is allocated. And unfortunately there is no standard way to tell whether any other pointer is pointing the same memory. So before free
you need to ensure yourself as a programmer that the memory is not required.
精彩评论