2

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

enter image description here

Rehan K
  • 193
  • 1
  • 3
  • 17

2 Answers2

2

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.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
1

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.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • could you please link to read . im having lot of troubles regarding c++ memory handling and multitasking thank you – Rehan K Mar 03 '15 at 14:53
  • @RehanK First of all, this isn't C++ memory handling, this is C memory handling. C++ uses `new` and `delete`, not `calloc`. Secondly, in C++ you wouldn't even need to do manual memory handling... I'm not going to link you anything, you can Google all that you need yourself. StackOverflow even has [a list of good C++ books](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) which I recommend to check out and pick one. You should learn the basics of the language first before attempting manual memory management. – Emil Laine Mar 03 '15 at 15:03