C Programming - Memory Allocation - Discussion

Discussion Forum : Memory Allocation - Find Output of Program (Q.No. 3)
3.
What will be the output of the program?
#include<stdio.h>
#include<string.h>

int main()
{
    char *s;
    char *fun();
    s = fun();
    printf("%s\n", s);
    return 0;
}
char *fun()
{
    char buffer[30];
    strcpy(buffer, "RAM");
    return (buffer);
}
0xffff
Garbage value
0xffee
Error
Answer: Option
Explanation:
The output is unpredictable since buffer is an auto array and will die when the control go back to main. Thus s will be pointing to an array , which not exists.
Discussion:
16 comments Page 2 of 2.

Vishal said:   1 decade ago
The output is Garbage value. Because in the function definition, the character array 'buffer[30]' is declared as local. The scope of the local variable is limited within the blocks. But in the example, we are trying to return the address of a local array. This leads to problem & it is known as 'Dangling Pointer'.

To over come the problem, declare character array as 'static char buffer[30]' instead 'char buffer[30]' or declare character array Globally.

Rahul said:   1 decade ago
Take buffer variable as a globle to print RAM.

Shamu said:   1 decade ago
In order to print "RAM" how the program must be modified ?

Ranjit said:   1 decade ago
@Shilpi

Here buffer is basically a pointer, so it can be returned.

Shilpi said:   1 decade ago
But an array cannot exist in a return statement. It will cause an error.

Deepak said:   1 decade ago
May also cause stack smashing


Post your comments here:

Your comments will be displayed after verification.