c - C 指针错误,得到 exc_bad_access 代码=2,地址 0x100000000
问题描述
我对这个错误感到很困惑。我写了一个代码来分隔一组。当我运行它时,有时它可以工作,有时会出现 exc_bad_access code=2 错误。这是代码:
typedef struct vertexSet {
int numVertexSet;
int* set1;
int* set2;
} set;
set* bipatitionSet(int Vertex) {
if (Vertex%2){
Vertex +=1;
}
set* set;
set = malloc(sizeof(set));
set->numVertexSet = Vertex/2;
set->set1 = calloc(set->numVertexSet,sizeof(int));
set->set2 = calloc(set->numVertexSet,sizeof(int));
if (set == NULL) {
printf("Set memory allocated error!");
exit(1);
}
if (set->set1 ==NULL||set->set2==NULL) {
free(set);
printf("Set memory allocated error!");
exit(1);
}
for (int i=0; i< set->numVertexSet; i++) {
set->set1[i] = i;
set->set2[i] = i + set->numVertexSet;// got error here
}
return set;
}
运行时发现在for循环中set2地址发生了变化,set2[0]的值变成了-17958193。此错误有时会出现,但并非总是出现。有人可以解释为什么以及如何解决该错误吗?我检查了没有地址冲突。
解决方案
您不应该将变量命名为与类型相同的名称,因为变量会影响类型(您如何理解自己的代码,并区分类型和变量?)。在这种情况下,“阴影”与“覆盖”的含义相似。
作为一个例子,你malloc
是不正确的,因为sizeof(set)
将是变量的大小set
,一个简单的 4 或 8 字节指针,而不是 12-20 字节的大小struct vertexSet
。
推荐阅读
- laravel - 简写 isset 后跟 eval
- python - 如何通过单击外部窗口使 tkinter 窗口无法消失?
- macos - mac OSX 10.15.1 无法删除系统根证书
- c++ - 将 void* 参数转换为各种类型是 UB 吗?
- go - 查找与字符串匹配的结构字段类型
- javascript - 单击提交后使用 typescript/javascript 更改 div 的背景颜色
- excel - 在 SendMessage 中使用 WM_GETTEXT 时,VBA 崩溃
- c# - 编排多个 Azure 函数(powershell 和 C#)
- oauth-2.0 - 无法将图像文件添加到新的照片场景 [autodesk-forge] API Reality Capture
- html - 如何实际将我的 html 文件放到互联网/浏览器上,以便随机的人可以随时访问它?