为什么在这种情况下我不能使用分配的指针?

Why I cannot use allocated pointer in this case?

char    *ft_strjoin(int size, char **strs, char *sep)
{
    int     full_length;
    int     index;
    char    *read_head;
    char    *string;

    if (size == 0)
        return ((char *)malloc(sizeof(char)));
    full_length = ft_compute_final_length(strs, size, ft_str_length(sep));
    if (!(string = (char *)malloc((full_length + 1) * sizeof(char))))
        return (0);
    read_head = string;
    index = 0;
    while (index < size)
    {
        ft_strcpy(read_head, strs[index]);
        read_head += ft_str_length(strs[index]);
        if (index < size - 1)
        {
            ft_strcpy(read_head, sep);
            read_head += ft_str_length(sep);
        }
        index++;
    }
    *read_head = '[=10=]';
    return (string);
}

当我看到别人的代码时,我想知道这部分。

read_head = string;

我更改了仅使用分配指针的代码。

在这种情况下

string

因此出现“未分配正在释放的指针”的错误

我不明白为什么我必须使用另一个指针指向另一个指针?

是不是因为指向strcpy的指针和分配的指针不同?

对于初学者这个声明

if (size == 0)
        return ((char *)malloc(sizeof(char)));

没有意义,因为函数 return 是指向未初始化内存的指针。也许你的意思是

if (size == 0)
        return (char *)calloc( 1, sizeof(char));

即函数将return一个指向空字符串的指针。

在函数中,指针 read_head 正在更改,例如在该语句中

read_head += ft_str_length(strs[index]);

也就是说这样使用后,它不会指向最初分配的内存。从这个语句可以看出

*read_head = '[=13=]';

在 while 循环之后,指针指向构建字符串的终止零。

所以在 free 的调用中使用它会发出你遇到的错误。

所以这个声明

read_head = string;

允许在指针 string 中保留分配的动态内存地址,并使用将要更改的中间指针 read_head..

Why I cannot use allocated pointer in this case?

您不能直接使用 string 而必须使用额外的 read_head 变量的原因是因为您在循环中更改了 read_head(即 read_head += ... ).如果您直接在 string 上这样做,您将遇到问题,因为您需要知道 stringmalloced 值,以便您稍后可以调用 free

简单示例错误代码:

char *string = malloc(...);
string += someValue;        // Change the value of string
free(string);  <-------- ERROR because the value of string changed

简单示例好的代码:

char *string = malloc(...);
char *read_head = string;   // Give read_headthe same value as string
read_head += someValue;     // Change the value of read_head 
free(string);  <-------- FINE because the value of string did NOT change