Zul Huky
Zul Huky

Reputation: 333

Error : realloc(): invalid pointer

I want to realloc a char** inside a struct MotInfo**, it is a struct created by me. But I have an error when I try my realloc:

    int x;
    MotInfo** hashtable = malloc(TAILLE*sizeof(struct MotInfo*));
    for(x=0; x<TAILLE;x++)
    {
        hashtable[x] = NULL;
    }
    struct MotInfo* mot_info;
    int i;
    hashtable[5] = malloc(sizeof(struct MotInfo*));

    mot_info = malloc(sizeof(struct MotInfo*));
    mot_info->mot = "manger"; 

    mot_info->urls = malloc(2*sizeof(char*));
    mot_info->occurrences = malloc(2*sizeof(int));
    mot_info->taille = 2;
    for(i = 0;i<2;i++)
    {
        mot_info->urls[i] = "http://stackoverflow.com/questions";
        mot_info->occurrences[i] = 3;
    }
    printf("OK\n");
    hashtable[5] = mot_info;
    hashtable[5]->urls = realloc(hashtable[5]->urls, sizeof(char*)*2);

I have localised my error in the last line, but I have this error :

realloc(): invalid pointer:

Upvotes: 0

Views: 1956

Answers (2)

hopscotch
hopscotch

Reputation: 203

You did hashtable[5] = malloc(sizeof(struct MotInfo*)) but hashtable[5] is itself a pointer to struct MotInfo, so you probably would do hashtable[5] = malloc(sizeof(struct MotInfo))

Upvotes: 0

ilkkachu
ilkkachu

Reputation: 6517

struct MotInfo* mot_info;
mot_info = malloc(sizeof(struct MotInfo*));

mot_info is a pointer to struct MotInfo, but the space you allocate is only enough to hold a pointer, not the struct (which is likely to be bigger since it has at least four members). When you overstep the allocation, you may stomp on malloc`s bookkeeping.

hashtable[5] = malloc(sizeof(struct MotInfo*));       // (a)
mot_info = malloc(sizeof(struct MotInfo*));
hashtable[5] = mot_info;                              // (b)

That assigment on (b) loses the pointer to the block allocated at (a).

mot_info->urls = malloc(2*sizeof(char*));
hashtable[5] = mot_info;
hashtable[5]->urls = realloc(hashtable[5]->urls, sizeof(char*)*2);

I don't understand this either, aren't you reallocing to the same size?

Even if not, you probably shouldn't assign the return value of realloc to the same pointer immediately: it loses the pointer to the memory block if realloc fails.

Upvotes: 4

Related Questions