c - 在另一个明显独立的功能之后无法访问 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;
}
解决方案
错误在这里:
table = malloc(10);
这分配了十个字节的存储空间,这对于七个指针来说是不够的(循环change
循环七次)。你应该有类似的东西malloc(7 * sizeof(char *));
。
将来,当您遇到此类错误时,请尝试在valgrind
调试实用程序下运行该程序。在这种情况下,它会清楚地告诉您,您正在写超过分配给table
.
作为参考,sizeof(char *)
几乎总是四个或八个。
推荐阅读
- typescript - 在 Firebase 云功能中发送推送通知时出错
- nrules - NRules 问题:超类的规则匹配不起作用
- android - 我的回收站视图不显示所有图像和文本它只显示最后一个图像和名称“arraylist.size”时间
- reactjs - 防止在 React 中连续单击按钮
- jenkins - Jenkins 声明式:触发另一个管道并将阶段结果传递给当前管道
- php - 如何在 Visual Studio Online / Codespaces 上安装 PHP
- flutter - 当 FCM 数据消息到达时启动处于终止或后台状态的颤振应用程序(仅在 android OS 中)
- python - 如何使用python解析网站的标题?
- angular - 根本无法让 inputStyleClass 工作
- java - JavaFX中使用多条生产线并行处理一个队列中的多个任务