[英]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? 我在A周围堆栈损坏。如何解决此问题? 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 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. 声明意味着您有一个指向堆栈上声明的
automob
的指针,而&A
是指向堆栈上该位置的指针,这就是您最终传递给aloca
函数的内容。
*autos = (automob*)malloc(sizeof(automob));
allocates one automob
and assigns that pointer to A
, and this is fine. 分配一个
automob
并将该指针分配给A
,这很好。
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[i]
等效于*(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 *)
. autos
是指向堆栈的指针(这是您传递给函数的指针),并且堆栈上该位置的大小为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). 使用此代码,您尝试将您在堆栈上进行的所有分配存储在
&A
附近(在main
声明),最终您将覆盖堆栈保护程序(运行时用于保持堆栈完整性)。 To allocate n automob
s you only need this: 要分配n个
automob
您只需automob
:
*autos = (automob*)malloc(sizeof(automob) * n);
and you have the array of automob
s and you can access it like this: 并且您拥有
automob
的数组,您可以像这样访问它:
in aloca
: *autos[i]
is the i'th automob
, 在
aloca
: *autos[i]
是第i个automob
,
in read_autos
: *A[i]
is the i'th element, 在
read_autos
: *A[i]
是第i个元素,
and in main
: A[i]
is the i'th element. 并且
main
: A[i]
是第i个元素。
void aloca(automob **autos, int n)
{
*autos = malloc(n * sizeof(automob));
}
and so on 等等
you need to check for the error conditions like failed malloc or scanf 您需要检查错误条件,例如失败的malloc或scanf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.