Reputation: 659
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
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