C语言 条件fp==NULL是多余的,或者可能存在空指针解引用



我在CppCheck中得到上述错误,但我看不出出了什么问题。我想错误是我的代码找不到任何文件的原因,即使它们存在于我的计算机中。如有任何帮助,不胜感激。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 80
char *getchoice(void);
void getfile(char *filename);
int main() {
char *choice; 
choice=getchoice();
getfile(choice);
return 0;
}
char *getchoice(void) {
char *filename;
filename=malloc(SIZE);
printf("Enter the name of the text file: ");
scanf("%30s",filename);
return filename;
}
void getfile(char *filename) {
FILE *fp;
fp=fopen(filename,"r");
if (fp==NULL){
printf("The entered file does not exist.");
printf("n");
}
else{
printf("The file exists.");
}
fclose(fp);
return;
}

为了清理这个程序,下面列出了要做的事情:

  • 处理malloc故障,导致scanfgetfile不通过NULL
  • 检查scanf是否成功执行了预期的转换次数,以确保filename包含有效的数据。
  • 使用perror给出mallocfopen失败的更准确的信息。
  • 避免将NULL传递给fclose,以防fopen失败。
  • free内存由malloc分配(不像fclose,free可以安全地通过NULL)。
#include <stdio.h>
#include <stdlib.h>
char *getchoice(void);
void getfile(char *filename);
int main(void) {
char *choice = getchoice();
if (choice)
getfile(choice);
free(choice);
}
char *getchoice(void) {
char *filename = malloc(80);
if (filename) {
printf("Enter the name of the text file: ");
if (1 != scanf("%79s", filename)) {
free(filename);
return NULL;
}
} else {
perror("malloc");
}
return filename;
}
void getfile(char *filename) {
FILE *fp = fopen(filename, "r");
if (fp) {
puts("File opened.");
fclose(fp);
} else {
perror("fopen");
}
}

相关内容

最新更新