2

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;
}
emperor_c
  • 99
  • 2
  • 9
  • 8
    You didn't allocate memory for `result`. – mnistic Jul 08 '21 at 16:33
  • 1
    `char *result = malloc(strlen(temp)+1);` – Barmar Jul 08 '21 at 16:36
  • 1
    @mnistic. Juts to add may favorite nitpick: The variable `result` *has* memory allocated to it. Exactly 8 bytes if we assume a 64 bit pointers. What has *not* been allocated is an array to hold the copied string that `result` is supposed to point at. – HAL9000 Jul 08 '21 at 20:38

1 Answers1

2

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 1
    "*otherwise, you would be getting a segmentation fault.*" - using uninitialized pointer would lead to undefined behavior. Segmentation fault is only one of the possibilities but anything can happen, including the case when `World` will be printed as expected. – Alex Lop. Jul 08 '21 at 18:23
  • You should probably mention memory leaks and freeing allocated memory and capturing the result of the function. – Jonathan Leffler Jul 08 '21 at 18:41
  • Just to add some explanation for someone who is not familiar with `malloc`: the memory allocated with `malloc` is not stored in `result`, it is not part of the variable `result`, neither does it belong to it. `result` is just a pointer, it tells us where the newly allocated memory is, so we can find it when we need it. The allocated memory block exist totally independent of any pointers pointing at it. – HAL9000 Jul 08 '21 at 20:47