这是我的代码:
void Available_firmware_version(){
char *version = (char *) malloc(2);
strcpy(version, "");
FILE *fp;
int status = 0;
char path[PATH_MAX];
fp = popen("swift list Manto", "r");
if (fp == NULL){
printf("Error: Popen is NULL \n");
return;
}
while (fgets(path, PATH_MAX, fp) != NULL){
version = (char *) realloc(version, strlen(version) + strlen(path));
strcat(version, path);
printf("%s\n", version);
}
status = pclose(fp);
if (status == -1) {
printf("Error: Popen not closed (pclose)\n");
return;
}
free(version);
}
当我执行代码时,我的程序崩溃了。输出是分段错误,在 pclose(fp) 命令之前。当我删除 realloc 程序运行良好。也许我对 realloc 做错了什么?