线程1:EXC_BAD_ACCESS(代码= 2,地址= 0x8)错误c ++ [英] Thread 1: EXC_BAD_ACCESS ( code=2,address=0x8) Error c++
问题描述
我正在开发c ++应用程序。我已经分配内存,但在superfile.cpp中得到错误线程1:EXC_BAD_ACCESS(代码= 2,地址= 0x8)
。这是我的代码:
I'm developing c++ application . I have allocated memory but im getting the Error Thread 1: EXC_BAD_ACCESS ( code=2,address=0x8)
in superfile.cpp. Here is my code :
superfile.h
superfile.h
struct Node{
Voxel *data;
Node *next;
};
superfile.cpp
int* cnt =(int*)calloc(_width*_height,sizeof(int));
Voxel *temp =(Voxel *)calloc(_width*_height,sizeof(Voxel));
Node *list=(Node *)calloc(_width*_height*2,sizeof(Node));
list[(_width*_height)+l].next = list[_width*yy + xx].next->next; // Thread 1: EXC_BAD_ACCESS ( code=2,address=0x8) Error c++
的变量是:
_width=60
_height=45
l=3
yy=4096
xx=-3345
有什么想法吗?谢谢
>
推荐答案
您分配的内存不够。这里, list
的大小是60 * 45 * 2 = 5400个元素。您正在尝试访问60 * 4096-3345 = 242415的元素。
You're allocating not enough memory. Here, the size of list
is 60*45*2=5400 elements. You're trying to access the 60*4096-3345=242415th element.
这是访问不属于与 list
相关联的内存的内存。第242415个元素不存在。这是SegmentationFault。
That's access to memory that doesn't belong to the memory associated with list
. The 242415th element doesn't exist. That's SegmentationFault.
您需要使用 calloc(_width * _height * 100,sizeof(...));
来处理这个。然而,你会浪费大量的内存。
You'll need to use something like calloc(_width*_height*100,sizeof(...));
to handle this. However, you'll waste lots of memory then.
此外,不要为 next
和 next-> code>。尝试此
Also, you never allocate memory for next
and next->next
. Try this
list[_width*yy + xx].next=calloc(50, sizeof(...));
list[_width*yy + xx].next->next=calloc(50, sizeof(...));
list[(_width*_height)+l].next = list[_width*yy + xx].next->next;
这里 50
只是随机数不知道你的 struct
消耗了多少空间。
Here 50
is just random number, I'm not sure how much space does your struct
consume.
这篇关于线程1:EXC_BAD_ACCESS(代码= 2,地址= 0x8)错误c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!