ptr*** 不工作
当代码必须在 main 中的第二个 for 循环中通过 c.foos 访问 foo 元素时,代码无法正常工作(段错误)。
它只正确显示第一个元素,然后在 i=1 时显示垃圾,在 i=2 时最终崩溃。
所以我想这与指针数学有关。
怎样做才正确呢?数据结构不允许更改(不,这不是作业,它是 这个数据结构)。
#include <stdio.h>
#include <stdlib.h>
typedef struct _foo {
int i;
} foo;
typedef struct _foo_container {
foo ***foos;
} container;
foo** init_foos(void) {
foo** f;
int i;
f = malloc(sizeof(foo*)*3);
for(i=0; i < 3; i++) {
f[i] = malloc(sizeof(foo));
f[i]->i = i*11+1;
}
return f;
}
int main(void) {
container c;
foo **foos;
foos = init_foos();
c.foos = &foos;
int i;
for(i=0; i < 3; i++) {
printf("%d %d\n", i, foos[i]->i);
}
for(i=0; i < 3; i++) {
printf("%d %d\n", i, (**c.foos[i]).i);
}
//memory leaks, I know
return EXIT_SUCCESS;
}
注意:这段代码似乎有效。我想自上次 gcc 升级以来也发生了一些事情,尽管我可能仍然做错了什么。
附录:抱歉大家错过了*3
,这个POC是我匆忙写的。实际代码确实通过 php 的 safe_emalloc() 分配了所需的指针数量。
The code is not working properly (segfault) when it has to access the foo elements through c.foos in the second for loop in main.
It only displays the fist element correctly, then at i=1 it shows garbage, and at i=2 it finally crashes.
So I guess it has to do with pointer maths.
How to do it correctly? The data structures are not allowed to change (no, it's not a homework, it's an oversimplified POC of this data structure).
#include <stdio.h>
#include <stdlib.h>
typedef struct _foo {
int i;
} foo;
typedef struct _foo_container {
foo ***foos;
} container;
foo** init_foos(void) {
foo** f;
int i;
f = malloc(sizeof(foo*)*3);
for(i=0; i < 3; i++) {
f[i] = malloc(sizeof(foo));
f[i]->i = i*11+1;
}
return f;
}
int main(void) {
container c;
foo **foos;
foos = init_foos();
c.foos = &foos;
int i;
for(i=0; i < 3; i++) {
printf("%d %d\n", i, foos[i]->i);
}
for(i=0; i < 3; i++) {
printf("%d %d\n", i, (**c.foos[i]).i);
}
//memory leaks, I know
return EXIT_SUCCESS;
}
Note: this code seemed to work. I guess something has happened since the last gcc upgrade too, though I may still be doing something wrong.
Addendum: sorry everyone for missing the *3
, I wrote this POC in a hurry. The actual code DOES allocated the number of needed pointers, via php's safe_emalloc()
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试:
我认为问题在于运算符优先级。如果您没有为表达式加上括号,则“[]”将在“*”之前求值。
Try:
I think the problem is about operators precedence. "[]" is evaluated before "*" if you don't parentesize your expression.
在
init_foo
中,您必须分配3 * sizeof(foo *)
。In
init_foo
you have to allocate3 * sizeof(foo *)
.我认为你的问题就在这里:
看起来你想要的是一个 foo 指针数组,但你只分配了一个 foo 指针。
尝试将其更改为这样:
I think your problem is here:
It looks like what you want is an array of foo pointers, but you only allocate a single foo pointer.
Try changing it to this:
您分配的内存块的大小与指向 foo 的指针的大小相同。但随后您立即将其索引为
f[i]
,其中i
最大为 2。因此,您正在访问尚未分配的内存。You're allocating a chunk of memory the size of a pointer to
foo
. But then immediately afterwards you index it asf[i]
withi
up to 2. So you're accessing memory you haven't allocated.