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

时间:2018-12-14 10:07:16

标签: c compiler-errors malloc heap valgrind

我有这个上下文:

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
    }
    */
}

主要这样称呼

// 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(),因为如果我给它一个文字字符串,则不会出现警告。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

更改为

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

文件名可能没有分配多少内存(1024字节)