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

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

Respuesta :

Answer:

The Pointer P becomes a dangling pointer.

Explanation:

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.

ACCESS MORE
EDU ACCESS