General discussion

Locked

regarding C programming

By parimal408 ·
Hello,
I have a problem that I can’t solve. Can you kindly solve it for me? The problem is like that:-

Consider the following three, C functions:

[P1] int *g(void);
{
int x=10;
return (&x);
}

[P2] int *g(void);
{
int *px;
*px=10;
return px;
}

[P3] int *g(void);
{
int *px;
px=(int*) malloc (size of (int));
*px=10;
return px;
}
Which of the above three functions are likely to cause problems with pointers?
a> Only P3 b> Only P1 and P3 c> Only P1 and P2 d> P1,P2 and P3

Please tell me what will be the answer given above with explation i.e, the detail process to solve this type of problem.

Thank You.

This conversation is currently closed to new comments.

3 total posts (Page 1 of 1)  
| Thread display: Collapse - | Expand +

All Comments

Collapse -

by stevef199 In reply to regarding C programming

All three functions are defined wrongly and
will generate a compile-time error. Notice
the semi-colon after the function name, this
should not be there.

-Steve

Collapse -

by ediaz In reply to regarding C programming

ignoring the fact of the semi colon, all P1 and P2 will fail beacuse they return an address to a volatile area, the stack. P3 has no problems, because it alloc memory and return it.

Collapse -

by Wayne M. In reply to regarding C programming

This sounds suspiciously like a homework problem, but here is my synopsis of the different functions.

In [P1], int x is declared locally to the function on the stack. The return is a pointer to this area of memory, but this area will be reallocated upon the next function call made. Although it is very bad practice, one can still retrieve the value upon the return of the function and before the next function call made.

In [P2], a pointer to memory is declared but no memory is ever defined to hold the value. This is the most dangerous of the three functions, as the value 10 is being written to an unknown area of memory. This may cause corruption in other areas of the program or system that might depending on the previous value, or the value 10 may be overwritten by others.

In [P3], the pointer to memory has been allocated. This still leaves a possibility of memory leaks or corruption as the malloc must be balanced by exactly 1 dealloc in all execution paths. For this reason, many C programmers avoid malloc and would probably allocate the memory area on the stack at a higher level and pass a pointer to memory into the function. This may be a more involved answer than you are looking for.

The key to understanding C pointers is to understand where the memory is being allocated, either stack or heap. Stack allocations are no longer protected once the function declaring them returns to a higher level. Heap allocations live until explicitly returned to the heap.

Back to Web Development Forum
3 total posts (Page 1 of 1)  

Related Discussions

Related Forums