首页 > 解决方案 > 在另一个明显独立的功能之后无法访问 Malloc 空间

问题描述

我在以下 change() 函数中遇到了 malloc 的问题。当 i = 5 时,当我读取并尝试将输入行保存在 s 中时,表 [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;
}

读取第六 (i=5) 行之前的值

读取第六 (i=5) 行后的值

标签: cgccmallocscanffgets

解决方案


错误在这里:

table = malloc(10);

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

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

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


推荐阅读