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 1 of 2.

Deepak said:   1 decade ago
May also cause stack smashing

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

Ranjit said:   1 decade ago
@Shilpi

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

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

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

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.

Amol said:   1 decade ago
To print RAM just return ("RAM") ;.

Caro said:   1 decade ago
I execute this code and it returns RAM. It is strange. I don't understand why.

Om awasthi said:   1 decade ago
Below code will return ram.

#include<stdio.h>
#include<string.h>

int main()
{
char *s;
char *fun();
s = fun();
printf("%s\n", s);
return 0;
}
char *fun()
{
static char buffer[30];
strcpy(buffer, "RAM");
return (char*)buffer;
}

Sharat said:   1 decade ago
Buffer array is already a char what is the need to typecast in last statement?


Post your comments here:

Your comments will be displayed after verification.