[英]Seg Fault when initializing array
我正在上課,並遇到分段錯誤。 根據我的理解,當您訪問尚未分配的內存或超出邊界時,應該發生seg錯誤。 '當然我要做的就是初始化一個數組(雖然相當大)
我只是誤解了如何解析二維數組? 錯誤放置綁定正是導致seg錯誤的原因 - 我在使用嵌套for-loop
時錯了嗎?
教授提供了時鍾功能,所以我希望這不是問題所在。 我在Cygwin中運行此代碼,這可能是問題嗎? 源代碼如下。 也使用c99標准。
要非常清楚:我正在尋找幫助理解(並最終修復)我的代碼產生seg錯誤的原因。
#include <stdio.h>
#include <time.h>
int main(void){
//first define the array and two doubles to count elapsed seconds.
double rowMajor, colMajor;
rowMajor = colMajor = 0;
int majorArray [1000][1000] = {};
clock_t start, end;
//set it up to perform the test 100 times.
for(int k = 0; k<10; k++)
{
start=clock();
//first we do row major
for(int i = 0; i < 1000; i++)
{
for(int j = 0; j<1000; j++)
{
majorArray[i][j] = 314;
}
}
end=clock();
rowMajor+= (end-start)/(double)CLOCKS_PER_SEC;
//at this point, we've only done rowMajor, so elapsed = rowMajor
start=clock();
//now we do column major
for(int i = 0; i < 1000; i++)
{
for(int j = 0; j<1000; j++)
{
majorArray[j][i] = 314;
}
}
end=clock();
colMajor += (end-start)/(double)CLOCKS_PER_SEC;
}
//now that we've done the calculations 100 times, we can compare the values.
printf("Row major took %f seconds\n", rowMajor);
printf("Column major took %f seconds\n", colMajor);
if(rowMajor<colMajor)
{
printf("Row major is faster\n");
}
else
{
printf("Column major is faster\n");
}
return 0;
}
您的程序在我的計算機上運行正常(x86-64 / Linux),所以我懷疑您在調用堆棧的大小上遇到系統特定的限制。 我不知道你在Cygwin上有多少堆棧,但你的數組是4,000,000字節(32位int
) - 這可能很容易。
嘗試將majorArray
的聲明移出main
(在#include
之后直接放置) - 然后它將是一個全局變量,它來自一個可以更大的不同分配池。
順便說一句,這種比較是倒退的:
if(rowMajor>colMajor)
{
printf("Row major is faster\n");
}
else
{
printf("Column major is faster\n");
}
此外,要做這樣的測試,你真的應該重復許多不同陣列大小和形狀的過程。
我無法在您的代碼中找到任何錯誤,因此我編譯並運行它並按預期工作。
但是,您的代碼中存在語義錯誤:
start=clock();
//set it up to perform the test 100 times.
for(int k = 0; k<10; k++)
{
應該:
//set it up to perform the test 100 times.
for(int k = 0; k<10; k++)
{
start=clock();
此外,最后的條件應改為反向:
if(rowMajor<colMajor)
最后,為了避免其他人提到的os特定堆棧大小的問題,你應該在main()之外定義你的矩陣:
#include <stdio.h>
#include <time.h>
int majorArray [1000][1000];
int main(void){
//first define the array and two doubles to count elapsed seconds.
double rowMajor, colMajor;
rowMajor = colMajor = 0;
這個代碼在Linux下運行正常,我看不出任何明顯錯誤的東西。 您可以嘗試通過gdb進行調試。 像這樣編譯它:
gcc -g -o testcode test.c
然后說
gdb ./testcode
並在gdb中說run
如果崩潰,說where
和gdb告訴你,崩潰發生的位置。 然后你現在在錯誤的哪一行。
該程序在由gcc編譯時運行良好,並且在Linux中運行,Cygwin可能就是你的問題。
如果它在其他地方正確運行,你很可能試圖獲得比操作系統允許的更多的堆棧空間。 你在堆棧上分配4MB(1個整數),這對於在堆棧上“安全”分配來說太過分了。 malloc()和free()是你最好的選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.