gpt4 book ai didi

c - 系统调用参数 read(buf) 指向不可寻址的字节

转载 作者:太空宇宙 更新时间:2023-11-04 08:31:05 27 4
gpt4 key购买 nike

我正在尝试使用 Valgrind 调试我的代码,但我在读取函数时确实遇到了一些问题。

这是 Valgrind 日志:

==4333== Syscall param read(buf) points to unaddressable byte(s)
==4333== at 0x4F0C600: __read_nocancel (in /lib64/libc-2.18.so)
==4333== by 0x400AB7: my_read (get_next_line.c:132)
==4333== by 0x400B6C: get_next_line (tmp.c:25)
==4333== by 0x400B27: main (get_next_line.c:146)
==4333== Address 0x401000 is not stack'd, malloc'd or (recently) free'd
==4333==
==4333==
==4333== HEAP SUMMARY:
==4333== in use at exit : 4,106bytes in 1 blocks
==4333== total heap usage: 1 allocs, 0 frees, 4,106 bytes allocated
==4333==
==4333== 4,106 bytes in 1 blocks are definitely lost in loss record 1 of 1
==4333== at 0x4C277AB: malloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==4333== by 0x400A59: my_read (get_next_line.c:129)
==4333== by 0x400B6C: get_next_line (tmp.c:25)
==4333== by 0x400B27: main (get_next_line.c:146)
==4333==
==4333== LEAK SUMMARY:
==4333== definitely lost: 4,106 bytes in 1 blocks

这里是代码:

int    my_read(int fd)
{
char *str;
void *buff;
int x;

str = NULL;
if ((buff malloc(BUFFER_SIZE + 10)) == NULL)
return (NULL);
buff = NULL;
while ((x = read(fd, buff, BUFFER_SIZE)) > 0) //LINE 132
str = (str == NULL) ? my_strdup(buff) : my_strcat(buff, str);
return (str);
}

BUFFER_SIZE 定义为 4096。

我理解错误,但我不知道如何携带它。如果你们能帮我解决这个问题,那就太棒了。泰。

最佳答案

问题是

buff = NULL;

声明。为 buffer 分配空间后,您会忘记它并用 NULL 覆盖它,然后在调用 read() 时使用它.去掉那句话。

在从函数返回之前,您还需要free(buff);。否则每次调用 my_read() 时都会泄漏内存。

并且由于您返回一个指针,因此应该声明该函数:

char * my_read(int fd)

关于c - 系统调用参数 read(buf) 指向不可寻址的字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28335494/

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