C语言 free错误


#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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值