使用静态字符*

时间:2018-01-04 10:59:17

标签: c runtime-error valgrind

我发帖是因为我真的输了。 我做了一个重现getline行为的函数。

为此,我必须创建一个static缓冲区,用于保存下一行调用的下一行的开头。但是使我的缓冲区静态会产生一些错误。我知道我不能malloc static char *,而且我只是第一次初始化。但是当我回想起这个函数时,我认为缓冲区并不是真正的malloc,因为我在第二次和更多次调用时遇到了一些错误。我之后放了我的代码。

char *get_next_line(int fd)
{
    static char *s_buffer = NULL;
    char *f_buffer = malloc(sizeof(char));
    static int read_size = 0;

    f_buffer[0] = '\0';
    if (!s_buffer) {
        s_buffer = malloc(sizeof(char) * (READ_SIZE + 1));
        for (int i = 0; i < READ_SIZE + 1; i++)
            s_buffer[i] = '\0';
    }
    do {
        for (int i = 0; s_buffer[i] != '\0'; i++) {
            if (s_buffer[i] == '\n') {
                s_buffer = my_substr(s_buffer, i + 1, READ_SIZE);
                return (f_buffer);
            }
            f_buffer = my_realloc(f_buffer, s_buffer[i]);
        }
        read_size = read(fd, s_buffer, READ_SIZE);
        if (read_size <= 0)
            return (NULL);
        s_buffer[read_size] = '\0';
    } while (1);
}

函数my_reallocmy_substr正在运行,我对它们进行了测试。

首先,我在s_buffer[read_size] = '\0';上收到错误,写入无效。 正如我之前所说,我在read函数上遇到了一些错误。

我把日志:

==2004== Syscall param read(buf) points to unaddressable byte(s)
==2004==    at 0x4F3B1B0: __read_nocancel (in /usr/lib64/libc-2.25.so)
==2004==    by 0x4008D0: get_next_line (get_next_line.c:69)
==2004==    by 0x40094D: main (get_next_line.c:81)
==2004==  Address 0x5210ee6 is 0 bytes after a block of size 182 alloc'd
==2004==    at 0x4C2EB6B: malloc (vg_replace_malloc.c:299)
==2004==    by 0x400747: my_substr (get_next_line.c:36)
==2004==    by 0x400862: get_next_line (get_next_line.c:64)
==2004==    by 0x40094D: main (get_next_line.c:81)
==2004==
==2004== Invalid write of size 1
==2004==    at 0x4008FA: get_next_line (get_next_line.c:72)
==2004==    by 0x40094D: main (get_next_line.c:81)
==2004==  Address 0x5210ef8 is 18 bytes after a block of size 182 alloc'd
==2004==    at 0x4C2EB6B: malloc (vg_replace_malloc.c:299)
==2004==    by 0x400747: my_substr (get_next_line.c:36)
==2004==    by 0x400862: get_next_line (get_next_line.c:64)
==2004==    by 0x40094D: main (get_next_line.c:81)

我知道Syscall param read(buf) points to unaddressable byte(s)意味着我的缓冲区为NULL,但我认为它不是。 但是,我不知道无效的写作。

如果有人理解我的代码,我会在3天内被阻止,并且我仍然不理解这些错误。

感谢您的阅读,再见! (抱歉英语不好)

0 个答案:

没有答案