0

I am studying C programming and making some tests in Ubuntu with Geany. I have a question about pointers. When an array is declared in a function and then returned as a pointer, array values are lost in the main method. I could check this with a simple example:

#include <stdio.h>

char* msg ();

int main(int argc, char **argv)
{
    char* p = msg();
    int i;
    for(i=0;i<=10;i++)
        printf("i: %d, value: %c \n", i, p[i]);
    return 0;
}

char* msg (){
    char msg [] = "hello";
    return msg; 
}

The output is random values (excepting the first one that always is 'h'). I suppose that this is because the pointer passed out of the scope and the memory could be written by other functions.

But if the value of message is bigger enough (like thousands of characters for example or maybe less), values stand in the same memory place and I can read them despite of the array was created in other function.

What is the reason for this results?

Thank you so much.

  • How do you know that `'h'` is not random? – pmg Feb 19 '15 at 15:46
  • please, give me a good reason why are you trying this? Many errors in the same program. Even if you do `printf("%c\n", p[0]);` you invoke undefined behavior. – Iharob Al Asimi Feb 19 '15 at 15:47
  • I think that 'h' is not random because after executing the programme like ten times... – Adrián Campa Feb 19 '15 at 16:14
  • I am doing this kind of test to understand how the stack is handled and what values are saved in memory. I know that it is a wrong implementation but I am looking for logical answers. – Adrián Campa Feb 19 '15 at 16:18

1 Answers1

0

Returning a pointer to an automatic local variable invokes undefined behavior.

haccks
  • 104,019
  • 25
  • 176
  • 264