0

I would like to ask you about some doubt I have about memory allocation with calloc;

I am trying to create a bool 2d matrix which would be represented by 0 for false and 1 for true. I have the following code:

// Create a 2D array
int **createArrayBool(int row, int col){
    // Allocate memory for 2D array
    int **arr = (int**) calloc(row,sizeof(int*));
    for ( int i = 0; i < row; i++ ){
        arr[i] = (int*) calloc(col,sizeof(int));
    }
    return arr;
}

In main() I called the function:

int **arr2d = createArrayBool(2,2);

My doubt is that when I print the value let’s say at position arr2d[1][5] I got 0 but I only allocated col < 2 and I did not get an error.

Thank you for your answer.

  • 4
    Welcome to undefined behavior – Macmade Oct 14 '20 at 19:34
  • C doesn't promise to issue an error in such a case of [undefined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior). It doesn't promise anything at all, which means anything can happen, from no apparent effect to your worst nightmare. You simply have to design your code to not do that. – Nate Eldredge Oct 14 '20 at 19:39
  • 1
    To repeat an analogy I've used before, your question is like asking "I drove through a red traffic light and nothing happened. I was expecting the police to stop me from doing so. Why didn't they?" You got away with it... this time. Next time someone may crash into you. – Nate Eldredge Oct 14 '20 at 19:40
  • Does this answer your question? [Undefined, unspecified and implementation-defined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior) – Macmade Oct 14 '20 at 23:36

0 Answers0