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.

Mounika said:   6 years ago
Can anyone explain about buffer in C?

Hoang Pham said:   8 years ago
The return will be "RAM". The reason is very simple.

1. Return value will be copied to another place in stack.
2. Buffer will be free at the end of fun().

This concept is similar to return a local object in Cpp. The object will be copied to another place in a stack and the local object will be freed at the end of the function.

Primshapradheep said:   8 years ago
Thank you @Narendar.

Narendar kotrangi said:   9 years ago
char *fun()
{
char *buffer;
buffer=(char*)malloc(sizeof(char*));
strcpy(buffer, "RAM");
return (buffer);
}

This should work.

Saurabh said:   1 decade ago
DEVC++ is giving the answer RAM. I don't know why and also there is no error because of returning the address of local variable that is buffer, it is just giving the warning but answer is coming.

Jonty said:   1 decade ago
Why does static return RAM?

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

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;
}

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

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


Post your comments here:

Your comments will be displayed after verification.