簡體   English   中英

數組分段錯誤(核心轉儲)

[英]Segmentation fault (core dumped) with array

我的代碼有問題。 我對該問題進行了一些研究,但我發現的解決方案似乎不能解決我的問題。 大多數解決方案都說這是由於數組沒有索引。 這是我的代碼。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


int myrandom(int min, int max){
   return min + rand() / (RAND_MAX / (max - min + 1) + 1);
}

int main() {
    clock_t begin = clock();
    int T1[1000000];
    int T2[1000000];
    int T3[1000000];
    
    for (int i = 0; i < 1000000; i++) {
        T1[i] = myrandom(-10, 10);
        T2[i] = myrandom(-10, 10);
        T3[i] = T1[i]*T2[i];//<-- Getting Segmentation fault (core dumped) here
    }
    
    
    
    
    clock_t end = clock();
    double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
    printf("Program terminé en %f Secondes\n", time_spent);
}

你溢出你的堆棧。

int T1[1000000];
int T2[1000000];
int T3[1000000];

每個語句在堆棧上分配1000000*sizeof(int)字節。 這會導致堆棧溢出和其他無關內存的損壞。

嘗試使用動態分配:

int* T1=calloc(1000000,sizeof(int));
int* T2=calloc(1000000,sizeof(int));
int* T3=calloc(1000000,sizeof(int));

然后在使用后釋放它。 (PS: calloc & Co. 出錯時返回 NULL,所以檢查錯誤)

free(T1);
free(T2);
free(T3);

正如@JCWasm 指出的那樣,您正面臨着一個 stackoverflow 問題。 默認情況下根本不允許您請求的靜態內存(堆棧內存)量。 因此你的程序崩潰了。

供您參考:

  • gcc ,默認堆棧大小為 ~8MB參考
  • Windows (Visual Studio)上是 1MB 參考

現在,要解決您的問題,有兩種可能的方法:

解決方案1:(更通用和推薦)

使用動態內存:

int* T1=malloc(1000000*sizeof(int));
int* T2=malloc(1000000*sizeof(int));
int* T3=malloc(1000000*sizeof(int));

解決方案2:(僅當由於某種原因無法使用動態內存時)

所有編譯器都有一些增加堆棧大小的規定。 上面的鏈接演示相同。

  • 對於 gcc: > ulimit -s 32768 # sets the stack size to 32M bytes
  • 對於 Visual Studio:使用編譯器標志/F設置堆棧大小,例如/F 32768

其他 2 個答案是正確的,提到您應該使用堆( malloc()calloc()free() )。 但是還有另一種解決方案,但這不是首選:使用static變量。 static變量存儲在 .data 或 .bss 部分,因此它們不需要堆棧。 缺點是這個變量在運行過程中只存在一次,這使得static變量在使用多線程和其他場景時會出現問題。

盡可能選擇堆,但有些獨立環境可能沒有堆。 但是,假設sizeof int == 2 ,您不太可能獲得 2 MB 或更多 RAM,在這樣的系統上,總 RAM 更有可能是 64 KiB 或類似的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM