DennisVDB
DennisVDB

Reputation: 1357

C : freeing a reallocated pointer

I found out today that when I try to free a pointer that has been reallocated the program crashes and prints "Segmentation Fault".

A realloc() is called on this pointer (array) in order to sizeup the array and merge the old array and another one.

Further in the program I must free it, how can I bypass this problem without having to make some sort of buffer array, adding the 2 other arrays to it and then to free them?

  1. PARTICLE: structure
  2. newCount: sum of the size of the old array + array that is being added

Code:

group1->particleList = 
         (PARTICLE *) realloc(group1->particleList, newCount * sizeof(PARTICLE));

Upvotes: 0

Views: 411

Answers (3)

Ras
Ras

Reputation: 89

There should be no problem freeing a reallocated pointer. A program called valgrind can give you some valuable information about what is going on in your code.

Upvotes: 2

Jens Gustedt
Jens Gustedt

Reputation: 78923

Did you include "stdlib.h" ?

Casting the return of realloc and friends can hide the problem of having no prototype for it. Older compilers then take it to return an int, cast that int to a pointer type and the damage is done.

The problem that realloc would return 0 as others mention, shouldn't result in a fault when you free the buffer, but much earlier.

Upvotes: 1

John Bode
John Bode

Reputation: 123488

First, make sure you assign the result of realloc to a temporary variable; if the request fails, realloc will return NULL, and you'll lose your handle on the memory you've already allocated:

PARTICLE *tmp = realloc(group1->particleList, ...); // cast is unnecessary
if (tmp)
  group1->particlelist = tmp;
else
  /* handle realloc failure */

Make sure you aren't accidentally overwriting group1->particleList (possibly in your merge code?) before the free call. Even if it was getting overwritten with NULL in the event of a failed realloc call, free should be able to handle a NULL argument (basically, it'd be a no-op).

Upvotes: 0

Related Questions