1

I don't know, how to solve this problem. I have to use malloc inside void function. How can I use free for this case?

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

void function(char **string)
{
        *string=malloc(16*sizeof(char));
        *string="Hello World";
}

int main ()
{
        char *string;
        function(&string);
        printf ("%s\n", string);
        free(string); //not working
        return 0;
}

I can't use malloc inside function, because I would lose my string. And I don't know, how to use free in main. Can someone help me?

  • Sorry, I wanted to write "I can't use free inside function..." – Luboš Bartík Dec 12 '19 at 19:46
  • Does this answer your question? [strdup() - what does it do in C?](https://stackoverflow.com/questions/252782/strdup-what-does-it-do-in-c) – manveti Dec 12 '19 at 19:52
  • you can define in main a char** and give it to function (no & nor *), then free it correctly in main. But you need to strcpy "hello world" to the string, the = in function doesn't work either – B. Go Dec 12 '19 at 20:00

1 Answers1

0

You‘re overwriting the pointer, not writing to the memory. You’re then freeing a static string. You can copy the string to move it into that memory:

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

void function(char **string)
{
        *string=malloc(16*sizeof(char));
        strcpy(*string, "Hello World");
}

int main ()
{
        char *string;
        function(&string);
        printf ("%s\n", string);
        free(string);
        return 0;
}
Anonymous
  • 11,748
  • 6
  • 35
  • 57