如何在不接收非静态指针作为参数的情况下释放它

问题描述 投票:0回答:0

我不确定如何表达我的问题,但基本上我想要的是使用指针,

line
在这种情况下,对其执行 malloc 并放入数据,然后返回它。问题是,当我再次调用该函数时,如果我将
line
初始化为 NULL,据我所知这是一个泄漏,所以我需要以某种方式释放它。我不能更改函数接收的参数,也不能在接收它的程序中释放它,并且将其设为静态也是有问题的,因为它会导致无效或双重释放(由于某种原因,做
if (ptr) free(ptr);
不起作用,valgrind对此不满意它)。如果该方法只被调用一次,这不会是一个问题,但事实并非如此。

这是代码,如果大小 ft_realloc 释放并返回 NULL 指针 <= 0:

char    *get_next_line(int fd)
{
    int         newline;
    int         len;
    int         leido;
    char        *line;
    static char *buffer = NULL;

    len = 0;
    line = NULL;
    if (buffer && get_len(buffer))             //check if buffer is initialized and has data to process
    {
        newline = check_newline(buffer);  //check for \n
        if (newline != -1)
            return (print_buffer_line(buffer, newline));  //return the line in the buffer
        line = process_next_line(buffer, line, newline, 0);  //initialize and add data to line
        len = get_len(line);
    }
    else
        buffer = ft_realloc(buffer, BUFFER_SIZE + 1);

    leido = read(fd, buffer, BUFFER_SIZE);
    while (leido > 0)
    {
        buffer[leido] = '\0';
        newline = check_newline(buffer);
        line = process_next_line(buffer, line, newline, len);  //add data to the end of line
        if (newline != -1)
            return (line);
        len += leido;
        leido = read(fd, buffer, BUFFER_SIZE);
    }
    buffer = ft_realloc(buffer, 0);  //free and return NULL
    return (line);
}

process_next_line 根据要求:

char    *process_next_line(char buffer[BUFFER_SIZE], char *line, int newline, int offset)
{
    int len;

    if (newline != -1)
        len = newline + 1;  //if there is a \n, I only need space up to that character, included
    else
        len = get_len(buffer) + 1;  //if there is not, I add the whole buffer

    if (!line)
        line = ft_realloc(NULL, len + 1);
    else
        line = ft_realloc(line, get_len(line) + len + 1);  //making space for the new data
    line = append_line(line, buffer, offset);  //add the data of buffer to line starting at position offset
    buffer = move_buffer(buffer, newline); //discard all data previous to the \n
    return (line);
}

关于如何让它发挥作用的任何想法?如果我被迫使用静态指针,我需要知道如何只释放已经初始化的指针。

c pointers memory-management memory-leaks
© www.soinside.com 2019 - 2024. All rights reserved.