Suppose that a function dynamically allocates a block of memory with a local poi
ID: 3601190 • Letter: S
Question
Suppose that a function dynamically allocates a block of memory with a local pointer variable p pointing to the allocated block. Suppose further that there are no other pointers referencing that block of memory, and the function returns without doing a delete on p. Then
the pointer p becomes a dangling pointer.
B. the compiler will automatically deallocate the memory pointed to by p.
C. the program will suffer from memory leaks.
D. the returning function will throw the bad_alloc exception.
E. None of these
A.the pointer p becomes a dangling pointer.
B. the compiler will automatically deallocate the memory pointed to by p.
C. the program will suffer from memory leaks.
D. the returning function will throw the bad_alloc exception.
E. None of these
Explanation / Answer
A. The Pointer P becomes a dangling pointer.
Eg :-
int calculate(){
int *p = (int*)malloc(10);
*p = 10;
return p;
}
In this program, the scope of p is only with the calculate function block. Hence, once the compiler comes out of the function, it can no more access the pointer p or the memory location p is pointing to. To overcome the dangling pointer, we need to declare p as static, so that the scope of p is throughout the program.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.