Search code examples
cpointersdynamic-memory-allocationfreec-strings

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 = '\0';
    return (string);
}

When I saw others code I wonder the part of this.

read_head = string;

I change the code that use only allocated pointer.

In this case

string

So the error occures that "pointer being freed was not allocated"

I can't understand that Why do I have to use another pointer to point another pointer?

Is it happend because that to strcpy pointer and allocated pointer are different?


Solution

  • For starters this statement

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

    does not make a sense because the function returns a pointer to a non-initialized memory. Maybe you mean

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

    That is the function will return a pointer to an empty string.

    Within the function the pointer read_head is being changed as for example in this statement

    read_head += ft_str_length(strs[index]);
    

    That is after using it such a way it will not point to the initially allocated memory. As it is seen from this statement

    *read_head = '\0';
    

    after the while loop the pointer points to the terminating zero of the built string.

    So using it in a call of free will issue the error you got.

    So this statement

    read_head = string;
    

    allows to preserve the address of the allocated dynamically memory in the pointer string and to use the intermediate pointer read_head that will be changed..