gpt4 book ai didi

c - malloc 和 strcpy,非法访问,C

转载 作者:行者123 更新时间:2023-11-30 17:08:45 24 4
gpt4 key购买 nike

我已经阅读了很多相关内容,但找不到错误。

我有一个程序来判断是否在另一个较长的 CSV 字符串中找到字符串值(在下面的代码中,inIP 是 IPv4 地址,allow_hosts 应该是IPv4 地址的 CSV 列表,但它应该适用于任何字符串和 CSV 字符串列表)。

代码如下:

bool stringFound(char* inIP,char* allow_hosts){
bool found=false;
int i =0;
int j =0;
char* ip;
printf("strlen(allow_hosts)=%d\n",strlen(allow_hosts));
while(i<strlen(allow_hosts) && !found){
j=i;
while(allow_hosts[i]!=',' && i<strlen(allow_hosts)){
i++;
}
printf("jota = %d\n",j);
printf("i = %d\n",i);
printf("i-j+1 = %d\n",i-j+1);
ip = malloc(i-j+1);//1 more for '\0'
strncpy(ip,allow_hosts+j,i);//line 25, illegal access, problem one
printf("it copies=%s\n",ip);
ip[i-j]='\0';
found = strcmp(ip,inIP)==0;
//free(ip);//Problem two
if(found)
return found;
i++;
}
return found;

};

当我测试一次时,没有问题并且结果是正确的,但是,当我连续多次运行它时,第三次或第四次给我这个错误:

 malloc.c:2372: sysmalloc: Assertion 
`(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2]))
- __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0)
|| ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof
(struct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1))
& ~((2 *(sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) &&
((unsigned long) old_end & pagemask) == 0)' failed.
Aborted (core dumped)

据我所知,这是 malloc 的问题,但是当我用 调用它时,我分配的内存量是足够的

 stringFound("8.8.7.8","127.0.0.1,8.8.8.8");
stringFound("8.8.54.8","127.0.0.1,8.8.8.8,192.168.92.3");

正在打印

 jota = 10
i = 17
i-j+1 = 8
it copies=8.8.8.8

strlen(allow_hosts)=30
jota = 0
i = 9
i-j+1 = 10
//the error I showed above appears here

我还使用 Valgrind 对其进行了测试,只是将其命名为 valgrind ./myProgram,它显示:

 ==3406== Invalid write of size 1
==3406== at 0x402D763: strncpy (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3406== by 0x80485EB: stringFound (esta.c:25)
==3406== by 0x80486CC: test (esta.c:49)
==3406== by 0x8048803: main (esta.c:75)
==3406== Address 0x41fe0f0 is 0 bytes after a block of size 8 alloc'd

“test”是多次调用我的过程的函数,第 25 行在代码中被标记为“此处有问题”。

正如你所看到的,我在 free() 行中有一条评论。如果我使用这一行,错误将更改为

 Error in `./esta': free(): invalid next size (fast): 0x09d11008 
Aborted (core dumped)

我认为这两个错误是由同一原因引起的,但我没有找到错误

最佳答案

strncpy(ip,allow_hosts+j,i);//line 25, illegal access, problem one

是的,这应该会导致问题。我认为第三个参数应该是 i-j,而不是 i

关于c - malloc 和 strcpy,非法访问,C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33548983/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com