Jake Jackson
Jake Jackson

Reputation: 1245

Is it safe to call realloc() on the pointer you pass into function itself?

Note: I am not 100% confident with memory allocation and how it works, but I understand it for the most part.

When I see realloc() being used, I often see people using a new pointer to store the address space instead of using the same/old one. I am wondering if that is necessary.

Am I able to do the following?

char *string;
string = malloc(5 * sizeof(char));

...

string = realloc(string, 10 * sizeof(char));

More importantly, is this a safe thing to do?

Upvotes: 3

Views: 827

Answers (1)

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

(1) To answer the question of your title: no it is not, because realloc can give you a different pointer.

(2) To answer the question of your code: Neither. If realloc returns 0, meaning it can not honor your request to increase the size, you have lost your value of string but your old string has not been deallocated (memory leak).

Ad. 1: if you could realloc inside a function then you must either pass a double pointer or return the object.

Ad. 2: an example is:

char *string, *tmp;
string = malloc(5 * sizeof(char));

...

if ((tmp = realloc(string, 10 * sizeof(char))) == 0) {
    printf("Could not allocate more memory\n);
    return;
}
else
    string= tmp;

Upvotes: 3

Related Questions