gpt4 book ai didi

C - 动态内存字符串的不可寻址字节

转载 作者:行者123 更新时间:2023-11-30 16:23:57 25 4
gpt4 key购买 nike

我有这样的背景:

char* bname(char const *mypath) {    //basename
char* bnm = (char*) malloc((strlen(mypath)+1)*sizeof(char));
char lim='/';
char* z = strrchr(mypath, lim);
if (z) {
strcpy(bnm, z + 1);
} else {
strcpy(bnm,mypath);
}
return bnm;
}

void doX(int sockfd, char* filename) {
if (send(sockfd, filename, 1024, 0) == -1) {
// exit;
}

/*
No error with this one:
if (send(sockfd, "test", 1024, 0) == -1) {
// exit
}
*/
}

在 main 中专门调用它:

// argv[3] = test.jpg
char* fname= bname(argv[3]);
doX(socketd, fname);
free(fname);

编译:gcc -Wall -Werror -pedantic -std=c99 -ggdb3

Valgrind:valgrind --leak-check=full --tool=memcheck

Syscall param socketcall.sendto(msg) points to unaddressable byte(s)
==7096== at 0x4F5EC4D: send (send.c:28)
==7096== by 0x109197: doX (client.c:94)
==7096== by 0x1093A0: main (client.c:146)
==7096== Address 0x522e2f9 is 0 bytes after a block of size 9 alloc'd
==7096== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7096== by 0x108F38: bname (client.c:43)
==7096== by 0x109378: main (client.c:145)

我似乎找不到这个警告的原因,它很可能是 doX 的 send() ,因为如果我给它一个文字字符串,则不会出现警告。

感谢您的帮助。

最佳答案

改成这样

if (send(sockfd, filename, strlen(filename)+1, 0) == -1) {

filename 可能没有分配那么多内存(1024 字节)

关于C - 动态内存字符串的不可寻址字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53777540/

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