在嵌入式设备上使用 new 或 malloc 导致的 Segment Fault [英] Segment Fault caused by using new or malloc on embedded device

查看:32
本文介绍了在嵌入式设备上使用 new 或 malloc 导致的 Segment Fault的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 C++ 而不是 C 为我的 基于 MIPS 的嵌入式设备 构建我的应用程序.首先,我有一个链接问题,您可以在此处查看.此问题已解决,我可以成功构建我的应用程序.在我的代码中,我使用 malloc 函数进行内存分配,但是当我调用这个函数时,我得到 "Segment Fault" 消息.我用 new 操作符替换了 malloc,但结果是一样的.有关更多信息,请参阅以下代码:

I am trying to build my application with C++ instead of C for my MIPS based embedded device. First, I had a link problem that you can see here. This issue fixed and I could build my application successfully. In my code, I use malloc function for memory allocation, but when I call this function, I get "Segment Fault" message. I replaced malloc with new operator, but result was same. For more information, see the bellow code:

    int main(int argc, char** argv)
    {
            char* str = (char*)malloc(10 * sizeof(char));      //or   char* str = new char[10];
            strcpy(str, "Hello");
            return 0;
    }

当第 3 行被执行并调用 malloc 函数时,"Segment Fault" 消息出现在屏幕上.如果我使用 mipsel-elf-gcc 而不是 mipsel-elf-g++,我就没有这个问题.

When line 3 is executed and malloc function called, "Segment Fault" message appears on the screen. If I use mipsel-elf-gcc instead of mipsel-elf-g++, I don't have this problem.

这里出了什么问题?

推荐答案

malloc() 的库代码很可能是成熟和正确的.GNU 工具链库需要一个目标特定的移植层来将库粘合到您的目标硬件和/或操作系统上.对于 malloc() 和 C++ new 及其变体,相关系统代码位于 sbrk()(或 sbrk_r()> 用于重入,尽管它本身通常是一个包装器 sbrk().

The library code for malloc() is likley to be mature and correct. GNU tool-chain libraries require a target specific porting layer to glue the library to your target hardware and/or OS. In the case of malloc(), and in C++ new, and their variants the relevant system code is in sbrk() (or sbrk_r() for re-entrancy, though that is usually itself a wrapper aropund sbrk()).

工具链供应商对 sbrk() 的实现很可能是一个通用的存根,而不是针对您的特定目标量身定制的.您需要为您的运行时环境实现它.

The tool-chain vendor's implementation of sbrk() is likley to be a generic stub and not tailored to your specific target. You will need to have implemented it for your runtime environment.

这篇关于在嵌入式设备上使用 new 或 malloc 导致的 Segment Fault的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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