2013-01-24 84 views
0

我有這樣的代碼:strcpy的字符指針中止

 char **arr; 
    char* line=NULL; 
    int i=0; 
    size_t len=0; 
    ssize_t read1; 

    fp=fopen("list.txt","r"); 
    if(fp==NULL) 
     exit(EXIT_FAILURE); 

    while((read1=getline(&line,&len,fp))!=-1) 
     i++; 
    fclose(fp); 

    fp=fopen("list.txt","r"); 
    if(fp==NULL) 
     exit(EXIT_FAILURE); 

    arr=(char**)malloc(i*sizeof(char*)); // i is a variable i use to know the number of lines 
    i=0; 

    while((read1=getline(&line,&len,fp))!=-1) 
    { 
     line[strlen(line)]='\0'; 
     arr[i]=(char*)malloc(strlen(line)+1); 
     strcpy(arr[i],line); 
     i++; 
    } 

當我嘗試strcpy程序crashes.Is一個malloc問題? 我很確定i夠大。 linechar*,最初爲NULL

編輯:我忘了這個程序是在Qt中。

+1

您不需要在C程序中投射'malloc()'的返回值。 –

+4

***「'i'是我用來知道行數的變量」*** - 那麼它爲什麼命名爲'i'而不是'numberOfLines' /'linesNumber'? – LihO

+0

如何定義「行」?什麼是len的定義/價值? –

回答

3

有一對夫婦的代碼,我會什麼,我相信應該工作意見的問題...:

// I **assume** that these are the definitions for these variables 
// based on your comments 
size_t len = 0; 
char *line = NULL; 
ssize_t read1; 

// I **assume** that i has a reasonable value here, but this is not good to assume, 
// what if the file is a line longer tomorrow? I hope that you calculate the number 
// of lines somehow, that would be "less bad" 
int i = 10; // 10 lines in the file, who knows ?!? 
char **arr; 

// don't bother casting... 
arr = malloc(i * sizeof(char*)); 
i=0; 

while((read1 = getline(&line, &len, fp)) != -1) { 

    // THIS LINE DOES NOTHING, so we can just remove it 
    // line[strlen(line)]='\0'; 

    arr[i] = line; // since you asked getline to allocate a buffer for 
        // you (line was NULL), you can just store the buffer directly 
        // it's YOURS 
    i++; 

    // THIS IS THE BIG ONE: 
    // it is needed because otherwise the NEXT call to getline will 
    // reuse the same buffer, which may not be big enough 
    line = NULL; 
} 

而且,以後進行清理,你應該做這樣的事情:

int j; 
for(j = 0; j < i; ++j) { 
    free(arr[j]); 
} 
free(arr); 
arr = NULL; // not necessary, but good practice to avoid double frees and such 
+0

謝謝,但仍然無法正常工作。我將編輯代碼更加清晰。 –

+0

+1:@EmilGrigore請做,因爲如果'getline()'做了這個規定的事情,那麼這段代碼是正確的(除了'i'的缺失檢查,這很容易成爲這個代碼塊中最糟糕的命名變量。 – WhozCraig

+0

@Emil,請定義「不起作用」,因爲我提供的代碼不應該崩潰到我所知道的最好的狀態。您是否嘗試添加像我的代碼中的「re'NULL'ing」行? –

2

你不測試,如果你有比原來的我

arr=(char**)malloc(i_ori*sizeof(char*));//i_ori is a variable i use to know the number of lines 
i=0; 

while((read1=getline(&line,&len,fp))!=-1 && i<i_ori) 

而且actualy更多的線,你從來沒有測試是否的malloc返回NULL!見https://stackoverflow.com/a/2280342/1458030

@Emil格里戈裏:當我嘗試STRCPY程序crashes.Is一個malloc 問題?我很確定我足夠大。

是的!你需要測試NULL。

如果您使用C++和Qt,爲什麼不使用容器,流?

+0

我相信我有相同的行數作爲我 –

+0

@EmilGrigore:那麼請編輯您的文章,包括一個[最小的測試案例](http://sscce.org),演示這一點。 –