2015-03-03 376 views
2

我在開發C++應用程序。我已經分配了內存,但即時獲取superfile.cpp中的錯誤Thread 1: EXC_BAD_ACCESS (code=2,address=0x8)。這裏是我的代碼:線程1:EXC_BAD_ACCESS(code = 2,address = 0x8)錯誤C++

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 

任何想法是什麼g在嗎?謝謝

enter image description here

+0

什麼是'xx'和'yy'? – ForceBru 2015-03-03 13:13:22

+0

@ForceBru xx = -3345和yy = 4096並聲明爲int xx =(int)floor(x + 0.5); int yy =(int)floor(y + 0.5); – 2015-03-03 13:16:44

+0

我的意思是,他們從哪裏來?是你手動設置這些值還是以某種方式進行評估? – ForceBru 2015-03-03 13:18:23

回答

2

你分配內存不夠。這裏,list的尺寸是60 * 45 * 2 = 5400個元素。您正嘗試訪問60 * 4096-3345 = 242415個元素。

這是對不屬於與list關聯的內存的內存的訪問。第242415個元素不存在。這是SegmentationFault。

你需要使用類似calloc(_width*_height*100,sizeof(...));來處理這個問題。但是,你會浪費大量的內存。

此外,您從不爲nextnext->next分配內存。試試這個

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消耗。

+0

仍然不工作的傢伙。請找到我編輯的問題。謝謝。我投票給你。 – 2015-03-03 13:41:24

+0

@RehanK,如果你不再給我叫'夥計' – ForceBru 2015-03-03 13:49:13

1

你在這裏提領一空指針:

list[(_width*_height)+l].next = list[_width*yy + xx].next->next; 
                 ^^^^^^ 

值在list[_width*yy + xx].next0,通過calloc的初始化。

+0

非常感謝你 – 2015-03-03 14:46:29

+0

你可以請鏈接閱讀。即時通訊有很多關於C++內存處理和多任務處理的問題謝謝 – 2015-03-03 14:53:33

+0

@RehanK首先,這不是C++內存處理,這是C內存處理。 C++使用'new'和'delete',而不是'calloc'。其次,在C++中,你甚至不需要手動進行內存處理......我不會將任何東西鏈接起來,你可以自己編寫所有你需要的東西。 StackOverflow甚至有[一個好的C++書籍列表](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list),我建議檢查並選擇一個。在嘗試手動內存管理之前,您應該首先了解該語言的基礎知識。 – emlai 2015-03-03 15:03:23

相關問題