任务如下:
/* 实验 6 任务 A*/
/* 将整个数组 ia 保存到二进制文件中名为“filename”的文件中 可以通过 intarr_load_binary() 加载的文件格式。返回 成功时返回零,失败时返回非零错误代码。数组 长度 0 应该生成一个包含空数组的输出文件。 */
/* 实验 6 任务 B*/
/* 从名为“filename”的文件加载一个新数组,即 之前使用 intarr_save_binary() 保存。返回一个指向a的指针 成功时新分配的 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
谁能告诉我为什么我的代码会导致段错误?非常感谢。
最佳答案
在 B 的代码中,NULL
被传递给行中的 fread()
if( (fread (&len, sizeof(int), 1, f) != 1 ) )
因此可能会导致段错误。
要解决此问题,请将 fopen()
返回的文件指针分配给 f
:
改变
if( NULL == fopen (filename, "rb") )
至
if( NULL == (f = fopen (filename, "rb")) )
还要检查传递给函数的参数是否有效。
关于c - 为什么我的代码会导致段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42604550/