I am learning about memory allocation in C and I would like clarification regarding accessing out-of-scope memory.
int* ptr;
int n, i;
n = 10;
ptr = (int*)calloc(n, sizeof(int));
My understanding: In the above statement, I have allocated 40-byte memory (10 * 4 byte) which allows me to store 10 integers? If I try to insert more than 10 integers into "ptr" without allocating more memory I should get an error?
But with the example below, I am able to insert and print 1000 integers without allocating more memory to "ptr".
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.\n");
// Get the elements of the array
for (i = 0; i < 10000; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < 10000; ++i) {
printf("%d, ", ptr[i]);
}
printf("\n%d\n", ptr[1000]);
printf("%d\n", ptr[5555]);
free(ptr);
}
Aren't I not suppose to get an error for trying to insert more elements/integers into my "ptr" array without allocating more memory to ptr?