Malloc space 在另一个明显独立的函数之后无法访问

Malloc space not accessible after another apparently indipendent function

我在以下 change() 函数中遇到 malloc 问题。当 i = 5 时,当我读取并尝试保存 s 中的输入行时,table[4] 更改并且调试器说:“<错误:无法访问地址 0xa696573> 处的内存”,即使在值是正确的。使用 scanf 而不是 fgets 或打印 table[3] 值时会出现同样的问题。

(我使用 gcc -std=gnu11 -g 在 Windows 10 的 Linux 子系统中的 Ubuntu VS Code 中进行编译和 gdb 调试)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char **table;

int change()
{
    char s[1025];
    for(int i = 0; i <= 6; i++)
    {
        fgets(s, 1024, stdin);
        //scanf(" %1024[^\n]%*c", s);
        table[i] = (char *) malloc(strlen(s) + 1);
        strcpy(table[i], s);
    }
}

int main()
{
    table = malloc(10);
    change();
    return 0;
}

values before reading sixth (i=5) line

values after reading sixth (i=5) line

错误在这里:

table = malloc(10);

这分配了 10 个字节的存储空间,space 不够七个指针(change 中的循环循环七次)。你应该有类似 malloc(7 * sizeof(char *)); 的东西。

将来,当您遇到此类错误时,请尝试 运行 valgrind 调试实用程序下的程序。在这种情况下,它会清楚地告诉你,你正在写超过分配给 table.

的 space 的末尾。

作为参考,sizeof(char *) 几乎总是四或八。