2017-03-05 104 views
-1

任务如下:为什么我的代码导致分段错误?

/* LAB 6 TASK A */

/* 保存整个阵列IA成二进制 文件格式称为 '文件名' 文件,可以通过加载intarr_load_binary()。返回 成功为零,或失败时返回非零错误代码。长度为0的 数组应产生包含空数组的输出文件。 */

/* LAB 6 TASK B */

/* 负载从所谓的 '文件名' 的文件的新数组,这是 使用intarr_save_binary以前保存()。在成功时返回一个指向 新分配的intarr_t的指针,或在失败时返回NULL。 */

对于A,我的代码如下:

int intarr_save_binary(intarr_t* ia, const char* filename) 
{ 
    int returnValue = 0; 
    unsigned int len = ia->len; 
    FILE *f; 

    if(NULL == (f = fopen (filename, "wb"))) 
    { 
     perror("fopen failed"); 
     returnValue = 1; 
    } 

    else if (fwrite (&len, sizeof(int), 1, f) == 1) 
    { // then write of length successful 

     if (fwrite (ia->data, sizeof(int), len, f) == len) 
     { 
      returnValue = 0; // indicate success 
     } 

     else 
     { // else, write of data failed 
      returnValue = 3; 
     } 
    } 
    else 
    { // else, failed to write len value to file 
     returnValue = 4; 
    } 

    fclose(f); // cleanup (writes last buffer to file) 
    return(returnValue); 
} 

而对于B,我的代码如下:

intarr_t* intarr_load_binary(const char* filename) 
{ 
    unsigned int len = 0; 
    FILE *f = NULL; 
    intarr_t* newia = NULL; 

    if(NULL == fopen (filename, "rb")) 
    { // then, fopen failed 
     perror("fopen failed"); 
     exit(EXIT_FAILURE); 
    } // end if 

    // implied else, fopen successful 

    if(NULL == (newia = malloc (sizeof(intarr_t)))){ 
     perror("malloc failed"); 
     fclose(f); 
     exit(EXIT_FAILURE); 
    } // end if 

    // implied else, malloc successful 

    if((fread (&len, sizeof(int), 1, f) != 1)) 
    { // then fread failed 
     perror("fread failed"); 
     fclose(f); 
     free(newia); 
     exit(EXIT_FAILURE); 
    } // end if 

    // implied else, fread for len successful 

    newia->len = len; 

    if(NULL == (newia->data = malloc (len*sizeof(int)))) 
    { // then malloc failed 
     perror("malloc failed"); 
     fclose(f); 
     free(newia); 
     exit(EXIT_FAILURE); 
    } // end if 

    // implied else, malloc successful 

    if(fread(newia->data, sizeof(int), len, f) != len) 
    { // then, fread failed 
     perror("fread failed"); 
     fclose(f); 
     free(newia->data); 
     free(newia); 
     exit(EXIT_FAILURE); 
    } // end if 

    // implied else, fread successful 

    fclose (f); 
    return newia; 
} // end function: intarr_load_binary 

谁能告诉我为什么我的代码的结果分段错误?非常感谢你。

回答

0

在用于B中的代码,NULL被传递到fread()在线路

if((fread (&len, sizeof(int), 1, f) != 1)) 

,因此它可能导致段错误。

为了解决这个问题,从分配返回fopen()f文件指针:
变化

if(NULL == fopen (filename, "rb")) 

if(NULL == (f = fopen (filename, "rb"))) 

还要检查是否传递给函数的参数是有效的。

+0

非常感谢!我已经提交了我的代码,并会让你知道结果。再次,我真的感谢你帮助我!你太棒了! –

+0

我再次遇到相同的错误。 –

+0

这是错误消息: 测试角落案例 \t intarr_save_binary(NULL,“foo”); \t ***分段故障*** –

相关问题