I have a very simple program to demonstrate the use of malloc function in C. I have allocated the size needed to store just one integer and stored the returned pointer in variable ptr.
The problem is, although I have set the malloc size for one integer (4 bytes in my PC), the code runs fine for even a large number of integers (int x = 95;
) when printf("%u\n", ptr + j);
is uncommented. But it gives an error when printf("%u\n", ptr + j);
is commented. Maybe it creates some adjacent memory block when trying to access for printf or something.
I think this has got to do something with the memory heap being used or not, but being a beginner in this, I would like an explanation for this.
Thank you.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int x = 95;
ptr = (int *) malloc(sizeof(int));
for (int j = 0; j < x; ++j) {
*(ptr + j) = 3;
//printf("%u\n", ptr + j);
}
for (int i = 0; i < x; ++i) {
printf("%d\n", *(ptr + i));
}
return 0;
}