2017-10-28 27 views
-1

如何讓這些大陣列更有效率?當我添加它們時,我遇到了分段錯誤,但是當我移除它們時,分段錯誤消失。我有幾個像這樣沒有顯示的大數組。我需要這些數組來處理我正在閱讀的文件。在下面的代碼中,我使用stdin而不是我通常使用的文件指針。使用後我也釋放每個大陣列。c編程更有效地使用大陣列

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <ctype.h> 

int main(void) { 
    int players_column_counter = 0; 
    int players_column1[100000] = {0}; 
    char *players_strings_line_column2[100000] = {0}; 
    char *players_strings_line_column3[100000] = {0}; 
    char *players_strings_line_column4[100000] = {0}; 
    char *players_strings_line_column5[100000] = {0}; 
    char *players_strings_line_column6[100000] = {0}; 
    char line[80] = {0}; 


    while(fgets(line, 80, stdin) != NULL) 
    { 
     players_strings_line_column2[players_column_counter] = 
     malloc(strlen("string")+1); 

     strcpy(players_strings_line_column2[players_column_counter], 
     "string"); 
     players_column_counter++; 
    } 

    free(*players_strings_line_column2); 
    free(*players_strings_line_column3); 
    free(*players_strings_line_column4); 
    free(*players_strings_line_column5); 
    free(*players_strings_line_column6); 
    return 0; 
} 
+3

使用'malloc'(和朋友)動態分配。 – usr

+0

分段錯誤最有可能是由於堆棧溢出(得到笑話?),當內存位於爲程序最重要的部分保留的特殊,小型和快速內存部分的邊界上時。正如@usr所述,使用malloc來糾正這個問題。 –

+1

自由變量?有趣的想法。你需要一本C書 –

回答

0

閱讀更多關於C dynamic memory allocation。學會使用malloc and calloc and free。請注意,malloccalloc(和realloc)可能會失敗,您需要處理該問題。見thisthat

call stack的大小是有限的(通常爲一個或幾個兆字節;實際的限制是操作系統和計算機的具體限制)。擁有超過幾千字節的呼叫幀是不合理的。但是callocmalloc可能允許分配幾千兆字節(實際限制取決於您的系統),或者當前筆記本電腦或臺式機至少有幾百兆字節。當地 - automatic variable - 超過幾百個元素的數組幾乎總是錯誤的(並且肯定是非常難聞的氣味)。

順便說一句,如果你的系統有getline(3),你可能應該使用它(如here)。同樣適用於strdup(3)asprintf(3)

如果您的系統沒有getline,或strdup,或asprintf,你應該考慮實施它們,或借用他們的一些免費軟件實現。

編譯所有警告和調試信息(例如gcc -Wall -Wextra -gGCC)。改進你的代碼,以獲得沒有警告。 使用調試器gdb(和valgrind)。當心undefined behavior(如buffer overflow s)和memory leaks

研究現有的free software(例如在github和/或一些Linux distribution)的源代碼以獲得靈感。