索引引用时出现段错误

segfault when referenced by index

convert_list_toarr 函数以链表作为参数。接下来,它将链表转换为数组。接下来,使用 print_matrix,我想将数组打印到控制台。

我在 print_matrix 中遇到段错误。当访问数组的元素arr[1][0].

我的代码

char        **convert_list_toarr(t_list **map_list)
{
    int     size;
    char    **arr;
    t_list  *tmp;
    int     i;

    i = 0;
    tmp = *map_list;
    size = ft_list_size(*map_list);
    arr = (char **)malloc(sizeof(char *) * size);
    while (tmp->next != NULL)
    {
        arr[i] = ft_strdup((char *)tmp->content);
        tmp = tmp->next;
    }
    ft_list_clear(map_list);
    print_matrix(arr, size);
    return (arr);
}

我的print_matrix

void        print_matrix(char **map, int size)
{
    int i;
    int j;

    i = 0;
    while (i < size)
    {
        j = 0;
        while (map[i][j] != '[=11=]')
        {
            write(1, &map[i][j], 1);
            j++;
        }
        i++;
    }
}

我的ft_strdup

/*
** Function:        char *ft_strdup
**
** Description:     The ft_strdup() function allocates sufficient memory for a
** copy of thestring s1, does the copy, and returns a pointer to it.
** The pointer may subsequently be used as an argument to the function free(3).
*/

char    *ft_strdup(const char *s)
{
    char    *dest;
    int     i;
    int     n;

    i = 0;
    n = ft_strlen(s);
    if (!(dest = (char *)malloc((n * sizeof(char)) + 1)))
        return (NULL);
    while (i < n)
    {
        dest[i] = s[i];
        i++;
    }
    dest[n] = '[=12=]';
    return (dest);
}

我的控制台输出 1111111111[1] 11491 segmentation fault

而不是 while (tmp->next != NULL) 你应该有:

while (tmp != NULL)

所有 while 循环转换为 for 循环会更安全、更易读:

char **convert_list_toarr(t_list **map_list) {
    int     size;
    char    **arr;
    t_list  *tmp;
    int     i;

    size = ft_list_size(*map_list);
    arr = malloc(sizeof(*arr) * size);
    if (arr != NULL) {
        for (tmp = *map_list, i = 0; tmp != NULL; tmp = tmp->next, i++) {
            arr[i] = ft_strdup((char *)tmp->content);
        }
        ft_list_clear(map_list);
        print_matrix(arr, size);
    }
    return arr;
}

这个 while 循环有两个问题

while (tmp->next != NULL)
{
    arr[i] = ft_strdup((char *)tmp->content);
    tmp = tmp->next;
}

第一个是你必须检查tmp是否等于NULL。

while (tmp != NULL)
{
    //...
} 

第二个是你忘记增加变量 i

while (tmp != NULL)
{
    arr[i++] = ft_strdup((char *)tmp->content);
    tmp = tmp->next;
}