Mar*_*tin -2 c c++ visual-studio-2012
我在C中处理大小((128*75)*(128*75))的数组.每当我将数组声明为全局时,就没有像
#include<stdio.h>
float buf[(128*75)*(128*75)]
int main()
{
//using buf in different functions works fine
}
Run Code Online (Sandbox Code Playgroud)
但每当我声明它使用malloc并使用main()获取访问冲突写入位置错误,
#include<stdio.h>
int main()
{
float * buf;
buf = malloc((128*75)*(128*75));
//using buf in different functions gives error
}
Run Code Online (Sandbox Code Playgroud)
它是什么原因?
malloc(x)只保留x 字节,而不是x 浮点数.
全局数组的大小确实是128*75*128*75浮点数.malloc-ed缓冲区的大小只有128*75*128*75 字节,即只能包含所需浮点数的四分之一(假设浮点数是平台上的4个字节).
这就是为什么您可能访问超出malloc-ed缓冲区的限制并获得段错误/访问冲突或在您的平台上调用的任何内容.
您可以使用calloc()或者您可以使用大小128*75*128*75*sizeof(float)作为参数malloc().