稍微修改我的代码后出现分段错误
我将复制相关行:
(声明)
typedef struct { /* per una entrada de la taula de posicion */
int f;
int c;
} pos;
pos *p_opo[9];
(在 main 中)
for (i = 0; i < num; i++) {
p_opo[i] = (pos *) calloc(n_fil * n_col / 2, sizeof (pos));
}
现在,仅在引入此行之后,代码就会在任意点处中断(在对给定库函数的调用中)。我怀疑我用这个破坏了一些东西,尽管我不知道是什么。
我想要的只是拥有一个可变大小数组的数组!
PD:num 是程序的一个参数。无论如何,我一直用 num=1 运行它。
I'll copy the relevant lines:
(Declarations)
typedef struct { /* per una entrada de la taula de posicion */
int f;
int c;
} pos;
pos *p_opo[9];
(in main)
for (i = 0; i < num; i++) {
p_opo[i] = (pos *) calloc(n_fil * n_col / 2, sizeof (pos));
}
Now, after only having introduced this lines, the code breaks in an arbitrary point (in a call to a given library function). I suspect I'm corrupting something with this, although I don't know what.
All I want is to have an array of variable size arrays!
PD: num is an argument of the program. I've been running it with num=1 anyway.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
num 应小于或等于 9。(p_opo 中分配的 0..8 个指针等于 9!)
请注意,在 C 中,如果发生内存泄漏等情况,您会在不同的位置出现错误。原因是通过更改某些代码、其他代码或数据可以重新排列,这可能最终导致分段错误。
所以问题很可能出在程序的另一部分。确保您打开了所有警告(如 gcc 中的 -Wall 选项),它可能会给您一些线索。
num should be less or equal to 9. (0..8 allocated pointers in p_opo equals 9 !)
Note that in C that you get errors in a different place in case of memory leaks, etc. The reason for this is that by changing some code, other code or data can be rearranged and this may end up in segmentation faults.
So the problem may very well be in another part of your program. Make sure you have all you warnings turned on (like the -Wall option in gcc), it may give you some clues.
如果您对
calloc
的调用请求大小为0
的内存,它可能会返回NULL
,如果您正在使用该内存,则可能会导致分段错误。因此,如果:或者不知何故,
您请求的内存大小为 0,那么 calloc 可以返回 NULL。
如果情况并非如此,那么我认为您没有足够的代码让任何人知道它为什么会出现段错误。您应该记住,在添加或更改一些似乎与实际错误的代码完全无关的代码之前,此类错误可能不会被注意到。
If your call to
calloc
asks for memory of size0
it may returnNULL
, and if you are making use of that memory it could be causing the segmentation fault. So if:or somehow
the size of the memory that you are asking for is 0, and so calloc can return NULL.
If this is not the case then I don't think that you have enough code up there for anyone to know why it is segfaulting. You should keep in mind that errors like this can go unnoticed until you add or change some code that seems to be totally unrelated to the code that has the actual error.
看到你转换了
calloc
的返回让我很怀疑。不要这样做,如果您忘记包含系统函数,这会导致典型的错误。如果您使用的是 64 位指针和 32 位
int
的机器,就会发生这种情况。Seeing you casting the return of
calloc
makes me suspicious. Don't do that, this leads to a typical error if you forget the include for the system function.This happes if you are on a machine with 64 bit pointers and 32 bit
int
.