C - 检查str是否为空

时间:2016-02-18 21:50:52

标签: c

在我的代码C中,我有**行,我需要检查*行是否为NULL,我写下面的代码可能会导致程序崩溃,我不知道为什么
我如何检查*行是否为NULL?
(我有0个警告,0个错误:-Wall -Werror -Wextra)
源代码:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include "libft/libft.h"
# define BUFF_SIZE  16

int     read_buffer(int const fd, int ret, char **endl, char **buffer)
{
    char    buff[BUFF_SIZE + 1];

    ret = read(fd, buff, BUFF_SIZE);
    buff[ret] = '\0';
    if (ret > 0)
    {
        *buffer = ft_strjoin(*buffer, buff);
        *endl = ft_strchr(*buffer, '\n');
    }
    return (ret);
}

int     get_next_line(int const fd, char **line)
{
    static char *buffer;
    char        *endl;
    int         ret;

    if (!buffer && !(buffer = ft_memalloc(BUFF_SIZE + 1)))
        return (-1);
    if (!*line) // HERE, program crash
        *line = my_strdup("");
    ret = 1;
    endl = ft_strchr(buffer, '\n');
    while (ret > 0)
    {
        ret = read_buffer(fd, ret, &endl, &buffer);
        if (endl)
        {
            buffer[endl - buffer] = '\0';
            *line = my_strdup(buffer);
            buffer = my_strdup(endl + 1);
            return (1);
        }
        if (ret == 0)
        {
            if (ft_strcmp("", *line) == 0)
            {
                *line = my_strdup(buffer);
                return (1);
            }
            return (0);
        }
    }
    return (ret);
}

int     main(void)
{
    int     fd;
    int     ret;
    char    *line;

    if ((fd = open("b.txt", O_RDONLY)) < 3 && fd != 0)
        return (-1);
    printf("%d\n", fd);
    ret = get_next_line(fd, &line);
    printf("%d - %s\n", ret, line);
    ret = get_next_line(fd, &line);
    printf("%d - %s\n", ret, line);
    ret = get_next_line(fd, &line);
    printf("%d - %s\n", ret, line);
    ret = get_next_line(fd, &line);
    printf("%d - %s\n", ret, line);
    return (0);
}

1 个答案:

答案 0 :(得分:4)

您正在*line中正确测试get_next_line()是否为空。问题是您从未在line中将NULL初始化为main()。由于它未初始化,因此在尝试使用它时会出现未定义的行为。

更改

char    *line;

char    *line = NULL;