Home > front end >  Dynamic memory allocation confusion
Dynamic memory allocation confusion

Time:03-12

I saw a tutorial where the instructor dynamically allocates memory for n*int size (n is not known in advance, user would give it as an input). Just out of curiosity, I have changed the code from calloc(n,sizeof(int)) to calloc(1,sizeof(int)) and I was expecting to see an error, but I did not face an error, and the code runs smoothly.

If I increment the pointer and it just continues without a problem, why should I use anything else but calloc(1,sizeof(int))?

#include <iostream>

using namespace std;

int main(){

    int n;
    printf("enter the size of array\n");
    scanf("%d",&n);
    int* A = (int*)calloc(1,sizeof(int));

    for(int i=0; i<n; i  ){

        *(A i) = i 1;
    
    }

    for(int i=0; i<n; i  ){

        printf("%d\n", A[i]);
        printf("%d\n", &A[i]);
    }

    // free(A)

    return 0;
}

CodePudding user response:

I was expecting to see an error

Your expectation was misguided. If you access outside the region of allocated storage, then the behaviour of the program is undefined. You aren't guaranteed to get an error.

Don't access memory outside of bounds. Avoid undefined behaviour. It's very bad. The program is broken.


Other advice: Avoid using calloc in C . Avoid using using namespace std;.

  • Related