可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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
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++
after debugging the values of the variables are:
_width=60 _height=45 l=3 yy=4096 xx=-3345
Any idea what is going on ? Thank you
回答1:
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.
That's access to memory that doesn't belong to the memory associated with list
. The 242415th element doesn't exist. That's SegmentationFault.
You'll need to use something like calloc(_width*_height*100,sizeof(...));
to handle this. However, you'll waste lots of memory then.
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;
Here 50
is just random number, I'm not sure how much space does your struct
consume.
回答2:
You're dereferencing a null pointer here:
list[(_width*_height)+l].next = list[_width*yy + xx].next->next; ^^^^^^
The value at list[_width*yy + xx].next
is 0
, as initialized by calloc
.