我目前正在开发一个项目,其中一个给定的函数似乎编译得很好,但是没有正常工作。
void tsunamiWriteFile(const char *baseResultName, int iter, double *U, double *V, double *E, int nelem, int nsub){
int i,j;
const char *basename = "%s-%08d.txt";
char filename[256];
sprintf(filename,basename,baseResultName,iter);
FILE* file = fopen(filename,"w");
fprintf(file, "Number of elem %d \n", nelem);
...
... }
当我用valgrind运行程序时,我得到了这个:
==4993== Invalid read of size 4
==4993== at 0x59D3778: __fprintf_chk (fprintf_chk.c:32)
==4993== by 0x4081B4: tsunamiWriteFile (stdio2.h:98)
==4993== by 0x408363: tsunamiCompute (tsunami.c:228)
==4993== by 0x401714: main (mainCompute.c:10)
==4993== Address 0x0 is not stack'd, malloc'd or (recently) free'd
任何想法为什么fprintf不起作用?
答案 0 :(得分:4)
错误:
Address 0x0 is not stack'd, malloc'd or (recently) free'd.
表示已收到NULL
指针且该函数尝试取消引用它。
您需要检查fopen
返回的指针:
if ((file = fopen(filename, "w")) != NULL)
fprintf(file, ...);
else
perror("fopen");