使用alloca函数崩溃,但是使用malloc可以 [英] Crash with alloca function but ok with malloc

查看:190
本文介绍了使用alloca函数崩溃,但是使用malloc可以的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请向我解释崩溃的原因.我有第3方代码,它在EXC_BAD_ACCESS中意外崩溃

Please explain me reason of crash. I have 3rd party code which unexpectedly crashes with EXC_BAD_ACCESS

static int overwrite_selector(struct srm_target *srm, MARFileRemoverProgressBlock progressBlock)
{
    srm->buffer = (unsigned char *)alloca(srm->buffer_size);

    if(overwrite_byte(srm, 1, 0xF6, progressBlock) < 0) return -1;
    return 0;
}

static int overwrite_byte(struct srm_target *srm, const int pass, const int byte, MARFileRemoverProgressBlock progressBlock)
{
  memset(srm->buffer, byte, srm->buffer_size);
  return overwrite(srm, pass, progressBlock);
}

崩溃发生在行memset(srm-> buffer,byte,srm-> buffer_size);看来srm-> buffer的分配内存有问题.但是,如果我将alloca替换为malloc,则一切正常(不会崩溃).

Crash occurs on line memset(srm->buffer, byte, srm->buffer_size); So seems problem with allocation memory for srm->buffer. But if I replace alloca to malloc then all is ok (no crash).

我在启用osx 10.9 ARC的系统上进行开发

I develop on osx 10.9 ARC enabled

我注意到苹果特有的一点:如果我在全局队列中运行代码,但是在主队列中运行一切正常,则会发生崩溃.

I noticed bit Apple specific: crash occurs if I run code in global queue but if on main queue all is ok.

推荐答案

听起来像是堆栈溢出,分配将从堆中分配,因此,如果您尝试分配过多,则会导致堆栈溢出,而malloc将从堆中分配更大的内存.当您用alloca使堆栈溢出时,您将无法知道

Sounds like a stack overflow, alloca will allocate from the stack and so if you attempt to allocate too much that will result in a stack overflow while malloc will allocate from the heap which is much larger. There is no way to know when you overflow the stack with alloca.

此外,请注意,由于alloca在堆栈上分配,因此从该函数返回的内存将不起作用,因为一旦退出该函数,该内存将不再可用.因此,如果您需要使用该功能之外的内存,则需要使用malloc.

Also, note that since alloca allocates on the stack returning that memory from the function won't work since that memory will no longer be available once you exit the function. So if you need to use the memory outside the function you will need to use malloc.

这篇关于使用alloca函数崩溃,但是使用malloc可以的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆