C程序出现段错误与指针比较警告,如何解决?
解决C语言密码管理器的段错误与警告问题
核心错误:strcmp调用的语法错误
你的段错误和编译器警告完全是因为getUserInput()函数里的strcmp参数写法错误:
原错误代码:
if(strcmp(createPass, userInput == 0)){ storeServiceEmailPass(); } else if (strcmp(readAllPass, userInput == 0)){ readAllData(); }
这里的userInput == 0是将数组与空指针做比较(数组永远不可能为NULL,因此编译器抛出警告),随后把这个布尔值(0)当作指针传给strcmp的第二个参数,属于非法指针操作,直接触发段错误。
正确写法:先调用strcmp,再判断返回值是否为0:
if(strcmp(createPass, userInput) == 0){ storeServiceEmailPass(); } else if (strcmp(readAllPass, userInput) == 0){ readAllData(); }
其他需要修复的问题
- 读取文件的模式错误
readAllData()里用"a"(追加写模式)打开文件不符合读取逻辑,应改为"r"(只读模式):
FILE * passfile = fopen("Passwords.txt", "r");
- 未检查文件操作的返回值
所有fopen调用都必须检查是否成功,避免空指针引发的未定义行为,比如createPassDoc()修改为:
void createPassDoc() { FILE * passfile = fopen("Passwords.txt", "w"); if (passfile == NULL) { perror("Failed to create file"); exit(EXIT_FAILURE); } fclose(passfile); printf("File Created.\n"); }
storeServiceEmailPass()和readAllData()里的fopen也需要添加同样的检查逻辑。
- 重复换行问题
fgets会读取输入的换行符,原代码中printf("%s\n", savedData)会导致输出重复换行,改为printf("%s", savedData)即可。
完整修正后的代码
#include <stdio.h> #include <stdlib.h> #include <string.h> void createPassDoc() { FILE * passfile = fopen("Passwords.txt", "w"); if (passfile == NULL) { perror("Failed to create file"); exit(EXIT_FAILURE); } fclose(passfile); printf("File Created.\n"); } void storeServiceEmailPass() { char ServiceEmailPassword[300]; FILE * passfile = fopen("Passwords.txt", "a"); if (passfile == NULL) { perror("Failed to open file for appending"); exit(EXIT_FAILURE); } printf("Please enter the following: Service, Email, Password.\n"); fgets(ServiceEmailPassword, 300, stdin); fprintf(passfile, "%s", ServiceEmailPassword); fclose(passfile); } void readAllData() { char savedData[5000]; FILE * passfile = fopen("Passwords.txt", "r"); if (passfile == NULL) { perror("Failed to open file for reading"); exit(EXIT_FAILURE); } printf("Here is your saved Data:\n"); while(fgets(savedData, 100, passfile)) { printf("%s", savedData); } fclose(passfile); } void getUserInput() { char userInput[255]; char createPass[] = "Store Service\n"; char readAllPass[] = "Show Passwords\n"; printf("What would you like to do?\n"); fgets(userInput, 255, stdin); if(strcmp(createPass, userInput) == 0){ storeServiceEmailPass(); } else if (strcmp(readAllPass, userInput) == 0){ readAllData(); } else { printf("Please enter a command such as: Store Service or Show Passwords.\n"); } } int main() { createPassDoc(); getUserInput(); return 0; }
内容的提问来源于stack exchange,提问作者WhatsEndoDoing
相关产品推荐
相关产品推荐

