Segmentation fault (core dumped)

Hello guys,
The below-given code compiles with a warning message function returns address of local variable [-Wreturn-local-addr]. When executed, I get the segmentation fault. Any guess ??

#include<stdio.h>
int *data();

void main()
{
    int *ptr;
    ptr = data();
    printf("Data: %d\n",*ptr);
}

int *data()
{
    int var = 0xff;  
    return &var;
}

The above warning implies that you are returning address of a local variable within a function, which you did in your code is the exact reason for the segmentation fault.

int *data()
{
    int var = 0xff;  
    return &var;       <---------- here
}

The memory allocated for the local variable in the stack memory gets automatically deleted once the function exits. In your case, the address of variable var is passed to pointer ptr before its exit. Then, you are trying to print the value from the same memory location, which is deleted automatically shortly after the function exits. In short, you are trying to print something which is not there.

You can skip this problem by using the static keyword.

int *data()
{
    static int var = 0xff; 
    return &var;
}
3 Likes

Thanks for the replay. Adding static to variable var solved my problem. But, why static? How static keyword works ??

Static keyword makes the variable exist throughout the program. Also, it makes the visibility of the variable limited to the function in which it is declared. In your case, the variable var will live until the program get terminated and also have a scope limited to function data.

2 Likes