0

I do not understand why I can use malloc with struct var **tableauVariables, but I receve an error with struct zone **tableauZonesMemoireLibres.

When debuging I receve :

At C:\Users\Onel\Desktop\test\test.c:33 Program received signal SIGSEGV, Segmentation fault.

My code :

#include <stdlib.h>

void tabInit(), tabDelete();

struct zone {
    int pos;
    int taille;
};

struct var {
    char id[10];
    struct zone  tableau;
};

struct var **tableauVariables;
struct zone **tableauZonesMemoireLibres;
int tailleMemoire= 10;

int main () {

    tabInit();

    tabDelete();

    return 0;
}

void tabInit() {
    tableauVariables = (struct var**) malloc(sizeof(struct var) * tailleMemoire);
    tableauVariables[0] = NULL;

    tableauZonesMemoireLibres = (struct zone**) malloc(sizeof(struct zone) * tailleMemoire);
    tableauZonesMemoireLibres[0]->pos = 0; //Line 33 segmentation fault
    tableauZonesMemoireLibres[0]->taille = tailleMemoire;
    tableauZonesMemoireLibres[1] = NULL;

    return;
}

void tabDelete() {
    int i;

    for(i=0; tableauZonesMemoireLibres[i] != NULL; i++)
        free(tableauZonesMemoireLibres[i]);
    free(tableauZonesMemoireLibres);

    for(i=0; tableauVariables[i] != NULL; i++)
        free(tableauVariables[i]);
    free(tableauVariables);
}
3
  • 1
    tableauVariables = malloc(sizeof(struct var *) * tailleMemoire); or simpler and more robust: tableauVariables = malloc(tailleMemoire * sizeof *tableauVariables ); Commented Nov 24, 2013 at 23:30
  • Learn to use valgrind for things like this. Commented Nov 24, 2013 at 23:31
  • Learn the language before even touching a debugger. Debuggers will teach you nothing. BTW: tableauZonesMemoireLibres : similar error. Commented Nov 24, 2013 at 23:34

1 Answer 1

1

You allocate an array, and cast it to a **.

This allocates an array of struct zone of size tailleMemoire.

tableauZonesMemoireLibres = (struct zone**) malloc(sizeof(struct zone) * tailleMemoire);

Maybe what you intended is

struct zone *tableauZonesMemoireLibres;
tableauZonesMemoireLibres = malloc(sizeof(struct zone) * tailleMemoire);
tableauZonesMemoireLibres[0].pos = 0; //Line 33 segmentation fault
tableauZonesMemoireLibres[0].taille = tailleMemoire;

Also, your tabDelete is totally wrong. You want one free foreach malloc:

void tabDelete() {
    free(tableauZonesMemoireLibres);
    free(tableauVariables);
}

On the other hand, if you really did want an array of pointers, then each element of that array needs to malloc'ed by itself.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I do want an array of pointers and you are right I forgot to malloc the first element before using it. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.