2013-01-24 47 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),演示这一点。 –