Ravit Teja
Ravit Teja

Reputation: 301

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?

free(s);

And before using free() , I want to check are there any other pointers pointing to s .

Upvotes: 2

Views: 2201

Answers (3)

Martin Beckett
Martin Beckett

Reputation: 96109

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'.

Upvotes: 1

taskinoor
taskinoor

Reputation: 46027

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.

Upvotes: 0

pmg
pmg

Reputation: 108968

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.

Upvotes: 7

Related Questions