0

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?

  • The c compiler typically doesn't generate code to check for buffer overflow errors. What you end up doing is overwriting memory that is not part of the array and which may belong to something else. What you risk doing is overwriting something important, it could be the whereabouts of Jimmy Hoffa, or a cure for hairloss, nobody can say for sure. Even if your program seems to work fine, your program may randomly crash later. Or even worse, it doesn't crash but continues working with corrupted data. The C language is famous for happily letting you shoot yourself in the foot when asked to. – HAL9000 Oct 09 '21 at 22:52
  • *If I try to insert more than 10 integers into "ptr" without allocating more memory I should get an error?* You may or may not see an error immediately. You might simply write other memory that belongs to your program and cause undesired or incorrect behaviors that may not show up for a long time. So, it's important in C when doing dynamic memory allocation you check your work carefully. There are analysis tools you can run that detect such issues in your code (valgrind, coverity, etc). – lurker Oct 09 '21 at 23:12

0 Answers0