使用灵活长度数组时的 Objective-C EXEC_BAD_ACCESS
我对我发现的一些行为做了一些测试,我想知道是否有人可以帮助我了解发生了什么。
我有一个名为 myStruct
的结构,如下所示:
typedef struct {
int size;
float floats[];
} myStruct;
我在其上运行此代码:
int main () {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *a = [[NSArray alloc] initWithObjects:@"0.2", @"0.5", @"0.5", nil];
NSLog(@"%@", a);
myStruct my;
my.size = a.count;
my.floats[0] = [[a objectAtIndex:0] floatValue];
my.floats[1] = [[a objectAtIndex:1] floatValue];
my.floats[2] = [[a objectAtIndex:2] floatValue];
NSLog(@"{ %lf, %lf, %lf }", my.floats[0], my.floats[1], my.floats[2]);
[a release];
[pool drain];
return 0;
}
它工作正常。但是,当我将结构声明更改为:
typedef struct {
float myVar;
int size;
float floats[];
} myStruct;
当我调用行 [a release]
时,我得到 EXEC_BAD_ACCESS。
谁能帮我理解这里发生了什么?
I have done some testing on some behavior I have found, and I was wondering if someone can help me understand what is going on.
I have a struct, called myStruct
, that looks like this:
typedef struct {
int size;
float floats[];
} myStruct;
And I run this code on it:
int main () {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *a = [[NSArray alloc] initWithObjects:@"0.2", @"0.5", @"0.5", nil];
NSLog(@"%@", a);
myStruct my;
my.size = a.count;
my.floats[0] = [[a objectAtIndex:0] floatValue];
my.floats[1] = [[a objectAtIndex:1] floatValue];
my.floats[2] = [[a objectAtIndex:2] floatValue];
NSLog(@"{ %lf, %lf, %lf }", my.floats[0], my.floats[1], my.floats[2]);
[a release];
[pool drain];
return 0;
}
It works fine. However, when I change the struct declaration to this:
typedef struct {
float myVar;
int size;
float floats[];
} myStruct;
I get EXEC_BAD_ACCESS when I call the line [a release]
.
Can anyone help me understand what is going on here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须实际为灵活的数组成员分配空间!此行:
仅为
size
(或第二个示例中的myVar
和size
)提供足够的堆栈空间。看起来,在失败的情况下,您正在覆盖堆栈上的a
,但实际上这两种情况都是错误的。要解决您的问题,您需要为结构的floats[]
成员分配空间:完成后不要忘记
free()
它!一个简单的例子 - 这个程序:
及其输出:
You have to actually allocate space for your flexible array member! This line:
Only makes enough stack space for
size
(ormyVar
andsize
from your second example). It appears that in your failing case you're overwritinga
on the stack, but really both cases are wrong. To fix your problem, you need to allocate space for thefloats[]
member of the structure:Don't forget to
free()
it when you're done!A quick example - this program:
and its output:
你没有为你的浮动分配任何内存 - 我很惊讶它没有更快崩溃!
您需要为 floats[] 指针分配一些内存吗?
经过快速测试后,我得到了 myStruct 的两个定义的 EXC_BAD_ACCESS :)
You're not allocating any memory for your floats - I'm surprised it's not crashing sooner!
Do you need to malloc some memory for the floats[] pointer?
After a quick test I get EXC_BAD_ACCESS for both definitions of myStruct :)