Consider the following three C functions:
int *g(void)
{
int x = 10;
return (&x);
}
int *g(void)
{
int *px;
*px = 10;
return px;
}
int *g(void)
{
int *px;
px = (int*) malloc (sizeof(int));
*px = 10;
return px;
}
Which of the above three functions are likely to cause problems with pointers?
View worked solution
Answer: C
To identify which functions cause pointer-related problems, let us analyze each function individually:
-
Function :
int *g(void) { int x = 10; return (&x); }The variable
xis a local automatic variable allocated on the stack. When the functiong()returns, its stack frame is deallocated, andxceases to exist. Returning&xreturns the address of a deallocated memory location, resulting in a dangling pointer. Accessing this pointer in the calling function leads to undefined behavior. -
Function :
int *g(void) { int *px; *px = 10; return px; }The pointer
pxis declared but not initialized, meaning it contains a garbage address (wild pointer). Attempting to dereference it with*px = 10writes to an arbitrary memory location, which typically causes a segmentation fault (undefined behavior). -
Function :
int *g(void) { int *px; px = (int*) malloc (sizeof(int)); *px = 10; return px; }This function dynamically allocates memory on the heap using
malloc(). Heap-allocated memory persists until it is explicitly deallocated usingfree(). Therefore, returningpxis perfectly safe and does not cause any immediate pointer-related errors (though the caller must eventually free it to avoid a memory leak).
Thus, only and cause pointer-related problems.
Free practice · Your answers on this page are not saved.
