У меня возникли проблемы с моей первой программой, использующей malloc. Моя проблема в том, что программа вылетает, когда выполняется строка free(). Я понятия не имею, почему это происходит и хотелось бы знать, как это предотвратить.free() на массив структур
#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;
}
Должно [лучше] (http://stackoverflow.com/q/605845/296974) be 'products = malloc (amount * sizeof (struct product));'. Хорошей альтернативой может быть 'products = malloc (amount * sizeof (* products));'. – glglgl
@glglgl Malloc casting - бесконечный аргумент здесь, на SO, поэтому я решил остаться в стороне и просто ответить на вопрос. –