Arnaud Rochez Arnaud Rochez - 1 year ago 61
C Question

Error with memory allocation with malloc(), can only add one item to table

So i got a strucure:

typedef struct Achat {
char aAcheter[25];
double quantite;
double prixUnitaire;
categorie rayon;
} achat;

Two static ints:

static int physicalSize = 0;
static int logicalSize = 0;

And a function:

int ajout (achat a, achat **table){
if (physicalSize == 0){
if ((*table = (achat *) malloc (5 * sizeof(achat))) == NULL){
perror ("malloc error");
return -1;
physicalSize = 5;

if (logicalSize == physicalSize){
if ((*table = (achat *) realloc(table, (physicalSize *= 2) * sizeof(achat))) == NULL){
perror("realloc error");
return -1;

*(table)[logicalSize] = a;
return logicalSize;

Basically, everything works fine when I call the function the first time, the item is added in the table and both the physicalSize and the logicalSize are updated.
The problem occurs when i call the function for the second time: I get a segmentation error. My guess would be that the malloc wasn't done well, even tho I can't see what I should change :/

Thanks for your answers :)

nb: the second argument (achat **table) is a single array, passed with the address of the table.

Answer Source

I suspect, by the superfluous parentheses, that your error lies in *(table)[logicalSize].
This treats table as a pointer to an array of achat*, when your note states that it is a pointer to a pointer to an array of achat.

The second interpretation would be written (*table)[logicalSize].

There's another typo in here : realloc(table, ...) should be realloc(*table, ...) to be consistent with the other uses of table (thanks MikeCAT!).

On a side note, please don't cast the result of malloc : it's useless at best, and harmful at worst.