Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope and lifetime of local variables in C

Tags:

c

I would like to understand the difference between the following two C programs.

First program:

void main()
{
    int *a;
    {
        int b = 10;
        a=&b;
    }
    printf("%d\n", *a);
}

Second program:

void main()
{
    int *a;
    a = foo();
    printf("%d\n", *a);
}

int* foo()
{
    int b = 10;
    return &b;
}

In both cases, the address of a local variable (b) is returned to and assigned to a. I know that the memory a is pointing should not be accessed when b goes out of scope. However, when compiling the above two programs, I receive the following warning for the second program only:

warning C4172: returning address of local variable or temporary

Why do I not get a similar warning for the first program?

like image 831
Kumar Avatar asked Mar 20 '14 08:03

Kumar


1 Answers

As you already know that b goes out of scope in each instance, and accessing that memory is illegal, I am only dumping my thoughts on why only one case throws the warning and other doesn't.

In the second case, you're returning the address of a variable stored on Stack memory. Thus, the compiler detects the issue and warns you about it.

The first case, however skips the compiler checking because the compiler sees that a valid initialized address is assigned to a. The compilers depends in many cases on the intellect of the coder.

Similar examples for depicting your first case could be,

char temp[3] ;
strcpy( temp, "abc" ) ;

The compiler sees that the temp have a memory space but it depends on the coder intellect on how many chars, they are going to copy in that memory region.

like image 135
Abhineet Avatar answered Sep 27 '22 16:09

Abhineet