问题
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?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/8956979/segment-fault-caused-by-using-new-or-malloc-on-embedded-device