Here is a fun one related to this module\'s topics, pointers and memory allocati
ID: 3684787 • Letter: H
Question
Here is a fun one related to this module's topics, pointers and memory allocation. It just popped up in a forum I monitor (I won't reveal which one here because I want you to dig out the answer yourself.
The writer says:
I encountered this question during discussion with interviewer -
If I have allocated 4 bytes of memory from malloc.
int *p = (int*) malloc(4);
now if I moved pointer by 4 byte.
P++;
And now pointer is pointing memory which is out of 4 byte of memory allocated by malloc. Let's assume that this memory has permission to read-write.
*p=4; That means pointer is going out of allocated memory.
Now consider a case where I allocated some memory but whenever my pointer moves out of allocated and write on that memory then I want to be informed but how??
I have only malloc and free to use.
Please give a written explanation only
Explanation / Answer
We have following code:
#include<stdio.h>
void main()
{
int* p = (int*) malloc(4); //here p is a pointer that point to memory location of 4 bytes
p++; //now pointer is pointing memory which is out of 4 byte of memory allocated by malloc
*p =4;
printf("%d", *p); //it will print the value as 4
}
now if we use const pointer in place of normal pointer then we can avoid going out of 4 byte of memory allocated by malloc as given below:
#include<stdio.h>
void main()
{
int* const p = (int*) malloc(4); //here p is a pointer that point to memory location of 4 bytes
p++; //p++ is not possible now
}
According to me, this much we can do, because accessing memory outside the malloc is not desirable and we can have a chance of memory leak also. Which is not a good programing practice
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.