Thread 1: EXC_BAD_ACCESS ( code=2,address=0x8) Error c++

匿名 (未验证) 提交于 2019-12-03 00:59:01

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!