Pointers MCQ questions 4, 6 explanation please
Doubt in MCQ questions
in question 4 ans will be B Memory Leak
int *ptr = (int *)malloc(sizeof(int)); ptr = NULL;
free(ptr);
there will be memory leak
because after memory allocation pointer points to NULL
and then we loose the access to that allocated memory
memory is allocated means occupied but we can’t access that so this is memory leak
this is not Dangling pointer
ans also Error will not come because every thing is correct
Q6 What will be the output of the following program? #include using namespace std;
int main() {
int arr[]={0,1,2,3,4};
int i, ptr;
for(ptr= arr, i=0; ptr+i <= arr+4; ptr++, i++) cout<< (ptr+i); return 0;
}
A) 01234 B) 024 C) 234 D) 12340
initially ptr points two first element 0 and i is 0
so firstly we print 0
and then both incremented hence ptr points to 1 and i is also 1
so ptr+i refer to 2 hence 2 will be printed
then again both incremented ptr points to 2 and is also 2
so ptr +i refer to 4
hence final output is 0 2 4