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

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

2 Answers  


Write, efficient code for extracting unique elements from a sorted list of array. e.g. (1, 1, 3, 3, 3, 5, 5, 5, 9, 9, 9, 9) -> (1, 3, 5, 9).

13 Answers   Intel, Microsoft, TCS,


main() { int i = 258; int *iPtr = &i; printf("%d %d", *((char*)iPtr), *((char*)iPtr+1) ); }

1 Answers  


main() { char *p; int *q; long *r; p=q=r=0; p++; q++; r++; printf("%p...%p...%p",p,q,r); }

1 Answers  


How to return multiple values from a function?

7 Answers  






Write a program to receive an integer and find its octal equivalent?

7 Answers  


main() { int a=2,*f1,*f2; f1=f2=&a; *f2+=*f2+=a+=2.5; printf("\n%d %d %d",a,*f1,*f2); }

6 Answers  


main() { char *str1="abcd"; char str2[]="abcd"; printf("%d %d %d",sizeof(str1),sizeof(str2),sizeof("abcd")); }

1 Answers  


main() { int i=4,j=7; j = j || i++ && printf("YOU CAN"); printf("%d %d", i, j); }

1 Answers  


main() { int a[10]; printf("%d",*a+1-*a+3); }

1 Answers  


main() { char *a = "Hello "; char *b = "World"; clrscr(); printf("%s", strcat(a,b)); } a. Hello b. Hello World c. HelloWorld d. None of the above

3 Answers   HCL,


Ramesh’s basic salary is input through the keyboard. His dearness allowance is 40% of basic salary, and house rent allowance is 20% of basic salary. Write a program to calculate his gross salary.

1 Answers  


Categories