Reputation: 31
I'm having trouble with my first program using malloc. My problem is that the program crashes when it executes the free() line. I have no idea why this is happening and would like to know how to prevent it from happening.
#include <stdio.h>
#include <stdlib.h>
struct product{
int cost;
char thing[20];
};
int main()
{
int amount;
scanf("%d", &amount);
getchar();
struct product *products;
products = (struct product *) malloc(amount);
for (int i = 0; i < amount; i++)
{
printf("Thing of %d ", (i + 1));
gets(products[i].thing);
printf("Cost of %d: ", (i + 1));
scanf("%d", &products[i].cost);
getchar();
}
free(products);
return 0;
}
Upvotes: 3
Views: 80
Reputation: 25752
Besides not allocating enough memory with malloc(), the function gets() is unsafe, deprecated and therefore should never be used.
If at any point used enters more characters than the buffer has available, you will get undefined behavior. Replace it with fgets() which allows you to specify the buffer size.
Upvotes: 1
Reputation: 3192
Actually you malloc()
, amount
of memory and uses amount * sizeof(struct product)
. It might work fine, but when you call free()
it causes the crash as you have written to some un-allocated memory and free()
tries to free memory which is not actually not allocated for you.
products = malloc(amount * sizeof(struct product)); // No casting too
There is no need to cast the value returned by malloc()
since it gets casted implicitly from a void*
the pointer to someOther*
.
Upvotes: 1
Reputation: 16718
You're not allocating enough memory. It should be:
products = (struct product *) malloc(amount * sizeof(struct product));
(malloc cast left in from original code, I'm not entering that debate.)
Upvotes: 7