c - 如何解决堆栈损坏错误?

标签 c stack dynamic-memory-allocation stack-corruption

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();
}

我在 A 周围出现堆栈损坏。我该如何解决这个问题?我认为这与分配有关,但我不知道如何解决。我真的看不到解决方案。

最佳答案

automob *A; 声明意味着您有一个指向在堆栈上声明的 automob 的指针,而 &A 是指向该位置的指针堆栈,这就是您最终传递给 aloca 函数的内容。

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

分配一个 automob 并将该指针分配给 A,这没问题。

现在,

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

是问题。 autos[i] 等同于 *(autos + i)autos 是指向堆栈的指针(它是您传递给函数的内容),堆栈上该位置的大小为 sizeof(automob *)。使用此代码,您尝试将所有分配存储在 &A 附近的堆栈上(在 main 中声明),最终您将覆盖堆栈保护(由保持堆栈完整性的运行时)。要分配 n 个 automob,您只需要这样:

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

并且您拥有 automob 数组,您可以像这样访问它:

aloca中:*autos[i]是第i个automob

read_autos中:*A[i]是第i个元素,

main 中:A[i] 是第 i 个元素。

关于c - 如何解决堆栈损坏错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54036303/

相关文章:

c - 引用 const 数组初始化 const 结构中的 const 数组

c - C中的Vigenere密码

c - 如何在内核模块(B)中调用内核模块(A)中的函数和变量,然后向用户空间发送通知?

c - 如何在c中的两个void指针之间交换内存

c++ - 执行内存分配以存储中断处理程序中获取的数据

c++ - 如何实现unsigned abs(int)?

java - 循环和堆栈,回文家庭作业

Java 数组列表栈

java - 有界堆栈实现

c++ - C++ 中的动态内存分配函数