2

I'm having a simple question to make, because I can't really find the way to return a string from a function and put it in another string. My code in C is this:

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

char *func();

int main()
{
        char *temp = malloc(sizeof(char) * 25);

        temp = func();
        printf("String received: %s\n", temp);

        return 0;
}

char *func()
{
        char str[25];

        strcpy(str, "HEY THERE!");
        printf("String sent: %s\n", str);

        return str;
}

I get this result: String sent: HEY THERE! String received:

Any idea how to do it properly? Thanks

STRATOSpeed
  • 99
  • 1
  • 2
  • 10

1 Answers1

2

Dynamic memory, yes, but it's used in the wrong place. Think about this code again:

char *temp = malloc(sizeof(char) * 25);
temp = func();

What you are doing is to allocate some memory for temp, and then assign it another value: the return value of func(), that's memory leak.

The correct method is to allocate memory in func(), and return the pointer to the allocated memory. Remember to free it when it's not used.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294