Ryan
Ryan

Reputation: 14649

How to free memory that is allocated in a function but address is returned by that function?

I want to know how to free the memory I've dynamically allocated. I know that the memory will get automatically freed after program termination, but what if this function was used as part of a daemon. I believe I would have a memory leak, no?

Here is the code. It is a simple string reverse function.

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

char *my_string_rev(char *string)
{
    // allocate memory to return the new string
    char *out = malloc (sizeof (char));

    assert(out);


    // do things here 
    // ..
    // ..

    return out;
}

int main()
{

   char *str = my_string_rev("true");

   free(str);

   return 0;
}

I've tried calling free(str) in main to find out that it won't work. Should I worry about freeing the memory returned by my_string_rev?

The above calling of my_string_rev does in fact work. When the string is longer than 4 characters. So when I call the function with "stackoverflow.com a b", I get this error:

Error in `./main': free(): invalid next size (fast): 0x088d2008 *

Is that because of malloc allocation? Should I be passing the length of the string to malloc?

Upvotes: 0

Views: 170

Answers (1)

Igor Pejic
Igor Pejic

Reputation: 3698

char *out = malloc(strlen(string) + 1);

+ 1 because strlen does not count '\0' character.

Upvotes: 1

Related Questions