Search code examples
cmatrixdynamicheap-memorycalloc

Problems with heap, PC freezes


I'm dealing with a dynamically allocated matrix. In particular I have this code (in C):

int i, n, m;
char **matrix;
matrix = (char **)calloc((n, sizeof(char *));
for (i = 0; i <= n; ++i) {
    matrix[i] = (char *)calloc(m, sizeof(char))
}

If 'n' is little enough the program works well but if I increase it drastically (I take a value close to the constant INT_MAX for example, in my case INT_MAX is 2.147.483.647) my PC freezes and I have to reboot it. I imagine this problem has to do with heap maximum size. Is it possible to prevent it somehow? Or do you suggest to put a reasonable upper limit to the growth of 'n'?

Thanks in advance!


Solution

  • INT_MAX is 2gb of ram. You're using up that much ram for each row, hence your matrix exceeds your ram capacity.