char *someFun1()

{

char temp[ ] = “string";

return temp;

}

char *someFun2()

{

char temp[ ] = {‘s’, ‘t’,’r’,’i’,’n’,’g’};

return temp;

}

int main()

{

puts(someFun1());

puts(someFun2());

}

Answers were Sorted based on User's Feedback



char *someFun1() { char temp[ ] = “string"; return temp; } char *som..

Answer / susie

Answer :

Garbage values.

Explanation:

Both the functions suffer from the problem of dangling
pointers. In someFun1() temp is a character array and so the
space for it is allocated in heap and is initialized with
character string “string”. This is created dynamically as
the function is called, so is also deleted dynamically on
exiting the function so the string data is not available in
the calling function main() leading to print some garbage
values. The function someFun2() also suffers from the same
problem but the problem can be easily identified in this case.

Is This Answer Correct ?    11 Yes 0 No

char *someFun1() { char temp[ ] = “string"; return temp; } char *som..

Answer / rahulkulkarni

Variables are in function calls, hence on heap space. Variable address is being returned by function and when function returns the allocated space is freed.

Now accessing returned address will result in : segmentation fault.

As address no longer allocated to function, results in invalid address accessed by process.
As variable address does not exist ( hence variable address also , as heap is freed).

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More C Code Interview Questions

how to return a multiple value from a function?

2 Answers   Wipro,


void ( * abc( int, void ( *def) () ) ) ();

1 Answers  


main() { extern out; printf("%d", out); } int out=100;

1 Answers  


main( ) { void *vp; char ch = ‘g’, *cp = “goofy”; int j = 20; vp = &ch; printf(“%c”, *(char *)vp); vp = &j; printf(“%d”,*(int *)vp); vp = cp; printf(“%s”,(char *)vp + 3); }

1 Answers  


why do you use macros? Explain a situation where you had to incorporate macros in your proc report? use a simple instream data example with code ?

0 Answers  






void main() { static int i; while(i<=10) (i>2)?i++:i--; printf(“%d”, i); }

2 Answers  


print a semicolon using Cprogram without using a semicolon any where in the C code in ur program!!

35 Answers   Tata Elxsi, TCS, VI eTrans,


what will be the output of this program? void main() { int a[]={5,10,15}; int i=0,num; num=a[++i] + ++i +(++i); printf("%d",num); }

3 Answers   Wipro,


Write a C program to print ‘Campus Force training’ without using even a single semicolon in the program.

3 Answers   Wipro,


main() { int i =10, j = 20; clrscr(); printf("%d, %d, ", j-- , --i); printf("%d, %d ", j++ , ++i); } a. 20, 10, 20, 10 b. 20, 9, 20, 10 c. 20, 9, 19, 10 d. 19, 9, 20, 10

4 Answers   HCL,


what is oop?

3 Answers  


main() { int i=10,j=20; j = i, j?(i,j)?i:j:j; printf("%d %d",i,j); }

2 Answers   Adobe, CSC,


Categories