为什么我的二维数组会导致 C 总线错误?
我正在尝试用 C 创建一个简单的二维数组,但显然遇到了一些内存问题。我的设置很简单,我不知道出了什么问题。我承认我对指针的理解不够,但我仍然认为这应该可行。有人能看出这里的缺陷吗?
typedef unsigned int DATUM;
DATUM **series_of_data;
void initialize_data()
{
*series_of_data = (DATUM *) malloc(1024 * sizeof(DATUM));
}
这会导致我的程序在运行时因总线错误而崩溃。
I'm attempting to create a simple 2D array in C but apparently running into some memory trouble. My setup is simple enough and I can't tell what's wrong. I admit that my understanding of pointers is insufficient, but I still think this should be working. Can anyone see the flaw here?
typedef unsigned int DATUM;
DATUM **series_of_data;
void initialize_data()
{
*series_of_data = (DATUM *) malloc(1024 * sizeof(DATUM));
}
This causes my program to crash with a bus error when I run it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
series_of_data 实际上没有分配。
您有多种方法来分配 2D 数组,要么使用行数组模型,该模型的缓存一致性较差,因此通常性能较差,要么使用 C 中的数值配方中建议的 Iliffe 向量,其中包括分配一个巨大的 h*w 内存块和一个包含行(或列)开头的侧指针数组:
数据很好地打包在内存中,因此缓存很满意,并且您可以保留 [][] 访问模式。
就速度而言,这与经典 DATUM* + 多项式访问方法的速度相差 +/-3%。
series_of_data is actually not allocated.
You have various way to allocates a 2D array, either using the array of rows model whcih has bad cache coherency and thus has usually bad performances or to use the Iliffe vector adviced in Numerical recipes in C that consists in allocating one huge h*w memory block and a side pointer array which contains the beginning of your rows (or columns) :
Data are nicely packed in memory, so cache are happy and you keep the [][] access pattern.
As a matter of speed this is in +/-3% speed of the classical DATUM* + polynomial access method.
series_of_data
是一个无效的指针 - 您没有将它分配给任何东西。当您尝试分配其内存位置 (*series_of_data = ...
) 时,它会将内容放入随机位置,这可能不会执行您想要的操作。您必须将series_of_data
指向有用的地方,例如,对于其中有16个用于
DATUM *
指针的槽的数组。series_of_data
is an invalid pointer - you don't assign it to anything. When you try to assign to its memory location (*series_of_data = ...
), it's putting stuff in a random place, which is likely to not do what you want. You have to pointseries_of_data
somewhere useful, e.g.for an array with 16 slots for
DATUM *
pointers in it.在分配给
*series_of_data
之前,您尚未分配series_of_data
指针。例如,如果
series_of_data
旨在成为一个数组,那么您需要编写如下内容:其中
n
是series_of_data
的长度大批。只有完成此操作后,您才能分配给
*series_of_data
。You haven't allocated the
series_of_data
pointer before you assign to*series_of_data
.For example, if
series_of_data
is intended to be an array then you would need to write something like this:where
n
is the length of theseries_of_data
array.Only after you have done this can you assign to
*series_of_data
.