No output produce after running the code. Blank and got nothing. Why?

Viewed 64

No output produce after running the code. Blank and got nothing. What is the problem ?

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

char* foo(){
    char temp[] = "World";
    char *result;
    strcpy(result, temp);
    return result;
}

int main(){
    printf("%s", foo());
    return 0;
}
1 Answers

The pointer result hasn't been assigned any memory here. So, You first need to allocate some memory to it, otherwise, you would be getting a segmentation fault.

One way of doing this would be allocating the memory dynamically, by using calloc or malloc here. It is found in stdlib.h header file. So, you have to include that. Then,

char *result = malloc(strlen(temp)+1);

would do the trick.

Related