535 views
0 votes
0 votes
char getstr(){
    static char s[] = "GATE2016";
    return s;
}
int main(){
    printf("%s", getstr());
    return 0;
}

Although I know I am returning an address using a character return type , and the return type must be char* getstr(); 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 .

1 Answer

Best answer
0 votes
0 votes

Here is the assembly code (inside main) for the correct version with "char *"

movl    $0, %eax  
call    getstr
movq    %rax, %rsi
movl    $.LC0, %edi
movl    $0, %eax
call    printf

Here is the assembly code (inside main) when "char *" is replaced with "char"

movl    $0, %eax
call    getstr
movsbl  %al, %eax
movl    %eax, %esi
movl    $.LC0, %edi
movl    $0, %eax
call    printf

As we can see and as mentioned din the question, the change is that, due to the prototype of getstr being char, in the second case, the returned value is truncated to just 8 bits. Now this 8 bits with higher bits padded with 0's or 1's (due to sign extension and x64 calling convention) will be used as an address in the second case and that causes segmentation fault. 

i.e., suppose address of s in first case is 0x 4F A1 23 43, in second case this becomes 0x 00 00 00 43.

Even the above is not a strict guarantee as we are using a char (integer) as an address and there might be alignment issue. 

If we keep it simple, answer is undefined behaviour :)

Related questions

0 votes
0 votes
1 answer
1
radha gogia asked Jul 28, 2015
980 views
int * p(void) { int *x; *x=10; return (x); } We create *x, and dereference it before assigning anything to it (x). Most likely, when we are declaring something on the sta...
1 votes
1 votes
1 answer
2
radha gogia asked Jul 29, 2015
678 views
#include<stdio.h int main(){ int test=0; float a = 3424.34; printf("hello \n %d",(test? a: 3)); return 0; }It is giving output as hello 0 ,I am unable to understand the l...
0 votes
0 votes
1 answer
3
radha gogia asked Aug 10, 2015
403 views
CASE A: CASE A: &#8234;#&lrm;include&#8236;<stdio.h int divide( int a, b) { return 7; } int main() { int a=divide(8,3); printf("%d",a); return 0; }CASE B :CASE B : #inclu...
0 votes
0 votes
1 answer
4