struct数组上的free()

Alu*_*bin 3 c malloc free

我使用malloc的第一个程序遇到了麻烦.我的问题是程序在执行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;
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*lin 7

你没有分配足够的内存.它应该是:

products = (struct product *) malloc(amount * sizeof(struct product));
Run Code Online (Sandbox Code Playgroud)

(malloc从原始代码中删除,我没有进入那场辩论.)