strcpy char指针中止

时间:2013-01-24 19:02:51

标签: c++ qt malloc 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时程序崩溃。问题是malloc吗? 我非常确定i足够大。 linechar*,最初为NULL

编辑:我忘记了这个程序在Qt。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)

另外,你永远不会测试malloc是否返回NULL !!见https://stackoverflow.com/a/2280342/1458030

  

@Emil Grigore:当我尝试strcpy程序崩溃时。是一个malloc   问题?我很确定我足够大。

是的!你需要测试NULL。

如果您使用的是C ++和Qt,为什么不使用容器,流?