2

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 .

Ravit Teja
  • 301
  • 6
  • 12
  • First thing you should do is remove `sizeof(char)` from your C vocabulary. It's an extremely ugly way of writing `1` that sets off an alarm in the mind of anyone reading your code. – R.. GitHub STOP HELPING ICE Mar 02 '11 at 20:42

3 Answers3

7

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.

pmg
  • 106,608
  • 13
  • 126
  • 198
  • `char *q = s` and you'll have two pointers pointing to the same location. :) –  Mar 02 '11 at 19:42
1

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

Martin Beckett
  • 94,801
  • 28
  • 188
  • 263
  • I often create a "smart free" macro for doing just this. It calls `free` and then sets the pointer to NULL. It works well for globally-accessible pointers, but it doesn't help if you've made a bunch of copies of the pointer. – bta Mar 02 '11 at 19:37
0

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.

taskinoor
  • 45,586
  • 12
  • 116
  • 142