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.
automob *A;declaration means that you have a pointer toautomobdeclared on stack, and&Ais the pointer to that location on stack, and this is what you finally pass toalocafunction.*autos = (automob*)malloc(sizeof(automob));allocates one
automoband assigns that pointer toA, and this is fine.Now,
is the issue.
autos[i]is equivalent to*(autos + i).autosis a pointer to the stack (it's what you passed to the function), and the size of that location on stack issizeof(automob *). With this code you try to store all the allocations you make on the stack near&A(declared inmain), and eventually you will overwrite the stack guard (that is used by the runtime to keep stack integrity). To allocate nautomobs 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'thautomob,in
read_autos:*A[i]is the i'th element,and in
main:A[i]is the i'th element.