Free () on array struct

I am having problems with my first program using malloc. My problem is that the program crashes when the line free () is executed. I have no idea why this is happening and would like to know how to prevent it.

#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;
}

      

+3


source to share


3 answers


You are not allocating enough memory. It should be:

products = (struct product *) malloc(amount * sizeof(struct product));

      



(The malloc cast is left in the source code, I'm not part of this discussion.)

+7


source


In fact, you malloc()

, amount

memory and use amount * sizeof(struct product)

. It might work fine, but when you call free()

it crashes as you wrote to some unallocated memory and free()

tries to free memory that isn't actually allocated for you.

products = malloc(amount * sizeof(struct product)); // No casting too

      



There is no need to specify a return value malloc()

as it receives an implicit expression from a void*

pointer to someOther*

.

+1


source


Also, by not allocating enough memory with malloc (), the gets () function is unsafe, deprecated, and therefore should never be used.

If, at any point used, more characters are entered than are available in the buffer, you will get undefined behavior. Replace it with fgets () , which allows you to specify the size of the buffer.

+1


source







All Articles