3

Here is the code that has a function GetString, this returns a char pointer. This char pointer is pointing to the string, which is in the stack. Now, why does the C compiler doesn't throw any warning when the address is returned for that string? Is the scope limited? Is it really a problem? Is "Hello" stored in Data Segment?

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

    char * GetString()
    {
       char *Hello = "Hello";

      return Hello;

    }

    int main(void)
    {
      printf("%s",GetString());
      return 0;
    }
Prawn Hongs
  • 441
  • 1
  • 5
  • 17
  • 2
    In general, you shouldn't rely on the possibility that the compiler will warn you about a particular piece of code, rather you should learn the rules and pitfalls of the language. – machine_1 Mar 21 '19 at 22:09
  • 1
    The code is in fact valid, that's why you don't get a warning. Don't hesitate to change the function return type to const char*, that you don't have to is the real problem. Not enough courage back in 1989. – Hans Passant Mar 21 '19 at 22:48

1 Answers1

5
char* GetString() 
{ 
    char Hello[] = "Hello"; 
    return Hello; 
}

would return a pointer to a stack allocated string.

char* GetString() 
{ 
    char* Hello = "Hello"; 
    return Hello; 
}

returns a pointer to a static string. (And you should really make it a char const* pointer because string literals are effectively (but not formally) const).

Even if you wrote

char* GetString() 
{ 
    char Hello[] = "Hello"; 
    return Hello; 
} 

however, the compiler is under no obligation to warn you about this. C is not Rust.

Clifford
  • 88,407
  • 13
  • 85
  • 165
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • But some compiler *can* warn about it given the right flags. I.e., you have to ask your compiler for it (if it is supported). – Bo R Mar 21 '19 at 22:07
  • @BoR Indeed, gcc and clang with default settings do warn if you're returning a pointer to a local: https://gcc.godbolt.org/z/VQ5Hds – Petr Skocik Mar 21 '19 at 22:10