0

In the below program

#include <stdio.h>

void fun1(char **p1)
{
    char ch1[] = "abc";
    *p1 = ch1;
}

void fun2(char **p2)
{
    char ch2[] = "def";
    *p2 = ch2;
}

int main()
{
    
    char *p1 = NULL;
    char *p2 = NULL;
    fun1(&p1);
    fun2(&p2);
    
    printf("string %s %s", p1, p2);
    return 0;
}

This gives me output as

string def def

I see both p1 and p2 are having same addresses. How is this working internally?

H Kumar
  • 37
  • 6
  • 1
    the lifetime of `ch1` ends when `fun1` returns. Same for `ch2` in `fun2` – 463035818_is_not_an_ai Jul 07 '23 at 11:31
  • 1
    both pointers are dangling pointers to local variables so are undefined behaviour – Alan Birtles Jul 07 '23 at 11:31
  • but wasn't it copied to the pointer variable? – H Kumar Jul 07 '23 at 11:33
  • 2
    no. Pointers are not arrays and arrays are not pointers. `char ch1[]` declares an array. `*p1 = ch1;` assigns the address of the first element of that array to `*p1` due to array to pointer decay – 463035818_is_not_an_ai Jul 07 '23 at 11:34
  • The problem in the given code lies in the fact that the character arrays `ch1` and `ch2` are local variables declared inside the respective functions `fun1` and `fun2`. These arrays are stored on the stack, and their memory is deallocated when the functions return. – chubercik Jul 07 '23 at 11:39
  • @463035818_is_not_an_ai in that case shouldn't I be getting segmentation fault, since I am trying to access memory that has been deallocated – H Kumar Jul 07 '23 at 11:42
  • In the `printf` statement, when you try to access the strings using `p1` and `p2`, you are accessing memory that is no longer valid. The behavior of the program becomes undefined, meaning that you cannot predict the output or behavior reliably. To fix this issue, you should allocate memory dynamically using `malloc` or `new` to ensure that the memory remains valid even after the functions return. Remember to deallocate the memory once you are done using it. – chubercik Jul 07 '23 at 11:42
  • you never get a guarantee for a crash. I mean what would that be good for? Your code is simply not valid C++. There are no rules that would explain what the code means or what it does when executed – 463035818_is_not_an_ai Jul 07 '23 at 11:43
  • though its explained in the duplicate. The answer goes in depth of explaining why it may seem to work – 463035818_is_not_an_ai Jul 07 '23 at 11:44
  • @chubercik OP should certainly *not* use malloc or new here – 463035818_is_not_an_ai Jul 07 '23 at 11:45

0 Answers0