Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segment Fault caused by using new or malloc on embedded device [closed]

Tags:

c++

c

embedded

arm

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;
    }

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.

What is wrong here?

like image 781
Mir Milad Hosseiny Avatar asked Dec 06 '25 12:12

Mir Milad Hosseiny


2 Answers

You write that your target platform is an ARMv7 processor, but your cross compiler is a mipsel compiler. You should download a toolchain for ARM. Sourcery Lite toolchains from Mentor Graphics are pretty good.

For instance, you can try to compile your program with arm-2011.03-41.

like image 199
Christophe Vu-Brugier Avatar answered Dec 09 '25 02:12

Christophe Vu-Brugier


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()).

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.

like image 31
Clifford Avatar answered Dec 09 '25 01:12

Clifford



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!