释放引用返回的 NSString 会导致崩溃
以下方法采用一个指向 NSString
的双指针,并用一个值填充它,如下所示:
@implementation Exp
- (int) func:(NSString**) dpStr
{
//------
*dpStr = [self func_2];
//------
}
现在它被这样调用:
int main ()
{
NSString * str = [[NSString alloc] init];
int retCode = [Exp func:&str];
// <----- Now here I'm able to access value returned by func ------->
[str release]; // <--- It is crashing here
}
谁能解释为什么它崩溃了?
The following method takes a double pointer to NSString
and populates this with a value, as follows:
@implementation Exp
- (int) func:(NSString**) dpStr
{
//------
*dpStr = [self func_2];
//------
}
Now it is being called like this:
int main ()
{
NSString * str = [[NSString alloc] init];
int retCode = [Exp func:&str];
// <----- Now here I'm able to access value returned by func ------->
[str release]; // <--- It is crashing here
}
Can anyone explain why it is crashing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这将分配一个空字符串:
这用一个显然已经自动释放的新字符串替换
str
的先前值; str 的旧值被泄漏:这尝试释放
str
的新值,该值已经平衡,因此这是过度释放并发生崩溃:在这种情况下,不需要前导的
+alloc/-init
和尾随的-release
,因为该对象是由 <代码>-func:。您所需要的只是:更好的是修改
-func:
以直接返回字符串:这样就不需要通过地址传递它。
This allocates an empty string:
This replaces the previous value of
str
with a new string which is apparently already autoreleased; the old value ofstr
is leaked:This attempts to release the new value of
str
, which is already balanced, so it's an overrelease and a crash happens:Neither the leading
+alloc/-init
nor the trailing-release
are needed in this case, as the object is provided by-func:
. All you need is:Better would be to modify
-func:
to return the string directly:Then there is no need to pass it by address.