Why does malloc() fail when there is enough memory?

后端 未结 5 1542
遇见更好的自我
遇见更好的自我 2021-01-08 00:21

I\'m using a server with 128GB memory to do some computation. I need to malloc() a 2D float array of size 56120 * 56120. An example code is as follows:

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-08 00:59

    int num = 56120,i,j;
    ls = (float *)malloc((num * num)*sizeof(float));
    

    num * num is 56120*56120 which is 3149454400 which overflows a signed int which causes undefined behavoir.

    The reason 40000 works is that 40000*40000 is representable as an int.

    Change the type of num to long long (or even unsigned int)

提交回复
热议问题