1

Why I am getting a segmentation fault in the code given below?

char getstr()
{
  static char s[]="Hiii2015";
  return s;
}

int main()
{
  printf("%s",getstr());
  return 0;
}

Although I know I am returning an address using a char return type , and the return type must be char* but still if I do like this only then I am getting null on gcc compiler and segmentation fault on another compiler so what is the reason for this

2 Answers 2

5

Your return type for getstr() is wrong.

It's just char, should be const char * or char *, i.e. a pointer.

As is, you're squishing the returned pointer down to char (probably just 8 bits) and then trying to access that very low address from printf() gives you undefined behavior.

You should have been getting a compiler warning for this.

Sign up to request clarification or add additional context in comments.

Comments

3

I am getting null on gcc compiler and segmentation fault on another compiler

Very profound sign of undefined behavior. In your code,

printf("%s",getstr());

actually invokes undefined behavior, as the supplied argument is not the proper type as expected by the supplied format specifier.

To elaborate a bit on this, quoting C11 standard, chapter §6.8.6.4, return statement,

If a return statement with an expression is executed, the value of the expression is returned to the caller as the value of the function call expression. If the expression has a type different from the return type of the function in which it appears, the value is converted as if by assignment to an object having the return type of the function.

So, s is returned as if converted to a char, representing a wrong value. That value, when being supplied as the argument to %s, creates all the issues via UB.

Upon encountering UB, the behavior is neither guaranteed nor be predicted.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.