Tom Boy
Tom Boy

Reputation: 659

Getting valgrind errors when trying to free int pointer array. Not sure why

This is my code/valgrind errors. Can someone help me figure out where I am going wrong.

struct Stores{
    int storeNumber;
    int *itemCost;
} Stores;

Stores store;
store = calloc(1,numStores*sizeof(store));

store.itemCost = (int*) calloc(1, numItems*sizeof(int)); //(numItems = 2)

store.itemCost[0] = 10;
store.itemCost[1] = 10;

free(store.itemCost);  <---- Error here
free(store);

The valgrind error I am getting:

--Invalid read of size 8

Upvotes: 1

Views: 113

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

First of all, without a typedef in place,

Stores store;

is wrong. Stores is not a type, anyway.

Considering

typedef struct Stores{
    int storeNumber;
    int *itemCost;
} Stores;

and then

Stores store;

you don't need to (rather, can not) calloc(), at all.

In case you want to play with allocate dynamic memory, you need to change

Stores *store;  // a pointer

and the related member access operators from . to ->, as applicable.

Moral of the story: Enable compiler warnings and pay heed to them.

That said, for the first calloc(), you did not cast the returned value, don't do it next time, either.

Upvotes: 2

Related Questions