#include <stdio.h> #include <string.h> #include <malloc.h> int IPset(char **str_accip, int *sgin){ char line[1024], *p = NULL; FILE *fp = NULL; memset(line, 0, 1024); *str_accip = (char *)malloc(sizeof(char) * 1024); fp = fopen("./whj.txt", "r"); if (fp != NULL){ while(fgets(line, 1024, fp)){ if((p = strstr(line, "inner:yes")) != NULL){ *sgin = 1; fclose(fp); return -1; } if((p = strstr(line, "acc_ip:")) != NULL){ line[strlen(line)-1] = '\0'; p+= 7; *str_accip = p; } } }else{ fcolse(fp); fp = NULL; return -2; } fclose(fp); fp = NULL; return 0; } int main(){ char *str = NULL; int sgin = 0; IPset(&str, &sgin); printf("%s, sgin=%d\n", str, sgin); if (str != NULL){ free(str); str = NULL; } return 0; } 编译没问题 运行的时候出现 *** glibc detected *** ./a.out: munmap_chunk(): invalid pointer: 0xbfc572a3 *** 大概原因是在用mallc申请了存储空间后所返回的指针在之后的操作中使所返回的指针的指向发生了变化 str指向p 正确代码: #include <stdio.h> #include <string.h> #include <malloc.h> int IPset(char **str_accip, int *sgin){ char line[1024], *p = NULL; FILE *fp = NULL; memset(line, 0, 1024); *str_accip = (char *)malloc(sizeof(char) * 1024); fp = fopen("./whj.txt", "r"); if (fp != NULL){ while(fgets(line, 1024, fp)){ if((p = strstr(line, "inner:yes")) != NULL){ *sgin = 1; fclose(fp); return -1; } if((p = strstr(line, "acc_ip:")) != NULL){ line[strlen(line)-1] = '\0'; p+= 7; strcpy(*str_accip, p); fclose(fp); return 0; } } }else return -2; } int main(){ char *str = NULL; int sgin = 0; IPset(&str, &sgin); printf("%s, sgin=%d\n", str, sgin); if (str != NULL){ free(str); str = NULL; } return 0; } 使用数组: #include <stdio.h> #include <string.h> #include <malloc.h> int IPset(char *str_accip, int *sgin){ char line[1024], *p = NULL; FILE *fp = NULL; memset(line, 0, 1024); fp = fopen("./whj.txt", "r"); if (fp != NULL){ while(fgets(line, 1024, fp)){ if((p= strstr(line, "inner:yes")) != NULL){ *sgin = 1; fclose(fp); return -1; } if((p = strstr(line, "acc_ip:")) != NULL){ line[strlen(line)-1] = '\0'; p += 7; strcpy(str_accip, p); } } }else{ fclose(fp); fp = NULL; return -2; } fclose(fp); fp = NULL; return 0; } int main(){ char str[1024]; int sgin = 0; memset(str, 0, 1024); IPset(str, &sgin); printf("%s, sgin=%d\n", str, sgin); return 0; }