提问人:omar ghazi 提问时间:11/11/2023 最后编辑:Some programmer dudeomar ghazi 更新时间:11/11/2023 访问量:50
为什么我的分体式功能有保护问题?[关闭]
why my split fumction have protection issue? [closed]
问:
我用 C 语言创建了我的 OWM ft_split 函数,该函数工作正常,但是当我使用特殊的机器人对其进行测试时,它会向我返回一个非保护的段错误原因。
Error in test 4: ft_split("\t\t\t\thello!\t\t\t\t", 9:'\t'):
malloc protection check for 2th malloc:
in _add_malloc malloc_mock.c:29:8
in malloc malloc_mock.c:75:10
-> in ft_substr ft_substr.c:26:15
in ft_split ft_split.c:74:3
in test_single_split test_split.c:72:2
in test_split test_split.c:83:8
in main test_split.c:101:2
: Should return NULL
看起来我在 substr 函数的第 26 行中有一个问题:
char *ft_substr(char const *s, unsigned int start,size_t len)
{
char *ret_array;
char *ret_empty;
size_t i;
i = 0;
//condition 1
if (!s)
return (NULL);
// condition 2
if (start > ft_strlen(s))
{
ret_empty = malloc(1);
if (!ret_empty)
return (NULL);
ret_empty[0] = 0;
return (ret_empty);
}
// condition 3
if (len > ft_strlen(s) - start)
len = ft_strlen(s) - start;
ret_array = (char *)malloc(len + 1); **// line 26 here**
if (!ret_array)
return (NULL);
// replissage
while (i < len)
{
ret_array[i] = s[start + i];
i++;
}
ret_array[i] = 0;
return (ret_array);
}
这是我的拆分函数:
#include "libft.h"
static size_t get_word_num(char const *s, char c)
{
char last;
size_t i;
size_t j;
last = c;
i = 0;
j = 0;
while (s[i])
{
if (last == c && s[i] != c)
j++;
last = s[i];
i++;
}
return (j);
}
static size_t get_word_len(const char *s, char c)
{
size_t i;
size_t j;
i = 0;
j = 0;
while (s[i] == c && s[i])
i++;
while (s[i + j] && s[i + j] != c)
j++;
return (j);
}
static char *ft_free(char *arr, size_t i)
{
size_t size;
size = i;
while (size > 0)
free(&arr[--size]);
free(arr);
return (NULL);
}
char **ft_split(char const *s, char c)
{
char **arr;
size_t i;
unsigned int j;
i = 0;
j = 0;
arr = (char **)malloc(sizeof(char *) * (get_word_num(s, c) + 1));
if (!arr)
return (NULL);
while (i < get_word_num(s, c))
{
while (s[j] && s[j] == c)
j++;
arr[i] = ft_substr(s, j, get_word_len(&s[j], c));
if (!arr[i])
ft_free(arr[i], i);
j += get_word_len(&s[j], c);
i++;
}
arr[i] = NULL;
return (arr);
}
`
请帮忙吗? 我找不到解决此问题的解决方案
答: 暂无答案
评论