我一直在用C编写这段代码,它有很多漏洞,我不知道如何清理。
当我在main上调用get_next_line时,我希望它返回.txt文件的下一行。
有人能帮帮我吗?
size_t ft_strlen(char *s)
{
size_t i;
if (!s)
return (0);
i = 0;
while (s[i] != '\0')
i++;
return (i);
}
char *ft_strchr(char *s, int c)
{
size_t i;
i = 0;
if (!s)
return (0);
while ((s[i] != '\0') && (s[i] != (unsigned char)c))
i++;
if ((s[i] == (unsigned char)c) || (c == '\0'))
return ((char *)&s[i]);
return (0);
}
char *ft_substr(char *s, unsigned int start, size_t len)
{
size_t i;
size_t j;
char *sub;
i = 0;
j = 0;
if (start >= ft_strlen(s) || !s || !len)
{
sub = malloc(1 * sizeof(char));
sub[0] = '\0';
return (sub);
}
while (s[start + j] != '\0' && j < len)
j++;
if (s[start + j] != '\0')
j++;
sub = malloc((j + 1) * sizeof(char));
if (!sub)
{
free(s);
return (0);
}
while (s[start] != '\0' && j > i)
sub[i++] = s[start++];
sub[i] = '\0';
//free(s);
return (sub);
}
char *ft_strjoin(char *s1, char *s2)
{
char *cat;
size_t i;
size_t j;
i = 0;
j = 0;
if (!s1)
{
s1 = malloc(sizeof(char) * 1);
s1[0] = '\0';
}
cat = (char *)malloc((ft_strlen(s1) + ft_strlen(s2) + 1) * sizeof(char));
if (!cat)
return (NULL);
while (s1[i] != '\0')
{
cat[i] = s1[i];
i++;
}
while (s2[j] != '\0')
cat[i++] = s2[j++];
free(s1);
cat[i] = '\0';
return (cat);
}
char *ft_content(int fd, char *content)
{
char *buf;
int buf_nb;
buf_nb = 1;
buf = (char *)malloc((BUFFER_SIZE + 1) * sizeof(char));
if (!buf)
return (0);
while ((!ft_strchr(content, '\n')) && buf_nb != 0)
{
buf_nb = read(fd, buf, BUFFER_SIZE);
if (buf_nb == -1)
{
free(buf);
free(content);
return (NULL);
}
buf[buf_nb] = '\0';
content = ft_strjoin(content, buf);
}
free(buf);
return (content);
}
char *get_next_line(int fd)
{
static char *content;
char *sub;
int i;
int len;
i = 0;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
content = ft_content(fd, content);
if (content == NULL)
return (NULL);
if (content[0] == '\0')
return (NULL);
while (content[i] != '\n' && content[i] != '\0')
i++;
sub = ft_substr(content, 0, i);
len = ft_strlen(content);
i++;
content = ft_substr(content, i, len);
return (sub);
}
int main(void)
{
int a = open("exemplo.txt", O_RDONLY);
printf("%s", get_next_line(a));
printf("%s", get_next_line(a));
printf("%s", get_next_line(a));
printf("%s", get_next_line(a));
return (0);
}
我已经做了几个变化,但我总是得到内存泄漏和分段故障。
我只想看看文件。
1条答案
按热度按时间a64a0gku1#
如果你使用的是编译器gcc或clang,你可以在编译程序时尝试使用命令行选项
-fsanitize=leak
,以检测任何内存泄漏。请参阅gcc手册中的这一页以获取更多信息。