Michael
Michael

Reputation: 447

Using realloc safely

I have a problem in the following code:

char* temp;
temp=realloc(dish->name,(sizeof(name)+1)*sizeof(char));
if(temp == NULL){
    return DISH_NULL_ARGUMENT;
}
dish->name=temp;

dish->name is char*, this code works! but when in a different function I write: free(dish->name), the program is crashing!

Upvotes: 0

Views: 102

Answers (1)

unwind
unwind

Reputation: 399833

What is name? Using sizeof on something that might be a pointer is very scary.

Also, please don't scale allocations by sizeof (char), it's always equal to 1 so it just adds noise and a general sense of the author being confused.

When using realloc() to grow something, it's good practice to grow it by more than a single element in most cases, since there's a risk it might grow again. Calling realloc() can be quite costly, so you should try to not do it very often.

Upvotes: 3

Related Questions