cstackdynamic-memory-allocationstack-corruption

How can I solve the stack corrupted error?


void aloca(automob **autos, int n)
{

    *autos = (automob*)malloc(sizeof(automob));
    for (int i = 0; i < n; i++) {
        autos[i] = (automob*)malloc(sizeof(automob));
    }
}

void read_autos(char* filename, automob **A, int *n)
{ 
    FILE *f_in = fopen(filename, "r");
    int i = 0, aux;
    if (f_in == NULL) {
        printf("Nu s-a gasit fisierul!");
        _getch();
        exit(0);
    }
    fscanf(f_in, "%d", n);
    aloca(A, *n);
    while (i < (*n)) {
        fscanf(f_in, "%d", &(*A)[i].locuri);
        fscanf(f_in, "%d", &(*A)[i].putere);
        fscanf(f_in, "%s", (*A)[i].marca);
        fscanf(f_in, "%s", (*A)[i].culoare);
        fscanf(f_in, "%d", &(*A)[i].an_fabricatie);
        i++;
    }
}

void main()
{
    int n;
    automob *A;
    read_autos("autos.in", &A, &n);
    _getch();
}

I get stack corrupted around A. How can I solve this problem? I think it is about the allocation but I don't know how to fix it. I really can't see the solution.


Solution

  • automob *A; declaration means that you have a pointer to automob declared on stack, and &A is the pointer to that location on stack, and this is what you finally pass to aloca function.

    *autos = (automob*)malloc(sizeof(automob));

    allocates one automob and assigns that pointer to A, and this is fine.

    Now,

    for (int i = 0; i < n; i++) {
        autos[i] = (automob*)malloc(sizeof(automob));
    }
    

    is the issue. autos[i] is equivalent to *(autos + i). autos is a pointer to the stack (it's what you passed to the function), and the size of that location on stack is sizeof(automob *). With this code you try to store all the allocations you make on the stack near &A (declared in main), and eventually you will overwrite the stack guard (that is used by the runtime to keep stack integrity). To allocate n automobs you only need this:

    *autos = (automob*)malloc(sizeof(automob) * n);

    and you have the array of automobs and you can access it like this:

    in aloca: *autos[i] is the i'th automob,

    in read_autos: *A[i] is the i'th element,

    and in main: A[i] is the i'th element.