Leuel Asfaw
Leuel Asfaw

Reputation: 339

free(): invalid pointer error on compilation after attempting to copy a string using a function

I am trying to copy a string using a function:

#include <stdlib.h>
#include <stdio.h>

char *_strdup(char *str);

/**
 * main - Entry point of my program
 *
 * Return: Always 0.
 */
int main(void)
{
    char *s;

    s = _strdup("Copied String");
    if (s == NULL)
    {
        printf("failed to allocate memory\n");
        return (1);
    }
    printf("%s\n", s);
    free(s);
    return (0);
}

/**
 * _strdup - This function returns a pointer to a new string
 * which is a duplicate of the string str
 *
 * @str: The string to be copied
 *
 * Return: On Success, this function returns a pointer to
 * the duplicated string. It returns NULL, if insufficent
 * memory was avaliable, and if str == NULL.
 */

char *_strdup(char *str)
{
        char *ch;

        if (str == NULL)
        {
                return (NULL);
        }
        ch = malloc(sizeof(*ch) * sizeof(*str));
        ch = str;
        return (ch);
}

As I run it, I get the following error:

Copied String
free(): invalid pointer
Aborted (core dumped)

It has copied the string, but as I try to free the memory space allocated it gives me an error. Why i it happening? How can I get around this?

Upvotes: 1

Views: 260

Answers (1)

Yunnosch
Yunnosch

Reputation: 26763

Here you malloc something which you could legally use free() on.
ch = malloc(sizeof(*ch) * sizeof(*str));.
Though I doubt the calculation of the size there....

Here, right in the next line, you throw that away and replace it by something which you can not legally use free() on.

ch = str;

And then you return it towards where it you attempt to use free() on it.

return (ch);

In total you basically attempt

free("Copied String");

Upvotes: 4

Related Questions