1

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;
        logicalSize++;
        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.

Arnaud Rochez
  • 578
  • 2
  • 4
  • 14

1 Answers1

1

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.

Community
  • 1
  • 1
Quentin
  • 62,093
  • 7
  • 131
  • 191
  • To add, I guess the first argument of `realloc()` should be `*table`, not `table`. – MikeCAT Aug 15 '16 at 16:15
  • Thank you for your answers, about the realloc i believe you're right, didn't test it yet so i didn't see it (thx :) ) And thanks Quentin i'll remove the cast before malloc (good to know it's bad to use it :3) – Arnaud Rochez Aug 15 '16 at 16:18
  • It works now Thank you very much <3 have been trying to fix it for one hour :D – Arnaud Rochez Aug 15 '16 at 16:22
  • @ArnaudRochez once the threshold period has ended, you will be able to mark this answer as correct (and the question as answered) with the green checkmark. Glad to have helped, and welcome to Stack Overflow :) – Quentin Aug 15 '16 at 16:24