Hi Matt,
Yep, as you suspected and as Anders has corrected, it is a C mistake; not stupid, just need to understand in C that when you define a pointer, it is only a pointer and doesn't point to anything (yet). Hence when you try and copy to it, things go wrong.
What will happen is strcpy will try and write to where this pointer points, but as it isn't initialised it doesn't point anywhere valid, hence bang.
In the following example, I've re-implemented the M3 Hard Fault handler to do more than loop forever - that'll get called on e.g. an invalid memory request:
#include "mbed.h"
extern "C" void HardFault_Handler() { error("Hard Fault!\n"); }
DigitalOut myled(LED1);
char * test;
int main() {
strcpy(test,"test");
while(1) {
myled = 1;
wait(0.2);
myled = 0;
wait(0.2);
}
}
Now when you run it, you'll get the mbed flashing Blue Lights of Death, and a message on a terminal saying "Hard Fault!" - It does indeed hang!
And as anders says, the solution is to ensure you allocate some memory to point to. Some by-examples:
char * test; // creates a char pointer called test, that can point to a character (or array of characters)
char test2[30]; // 30 characters are allocated, and test2 is a pointer to the first of them
test = test2; // now test also points at the first of the 30 characters
test[0] = 'a'; // set the first character pointed to by test to 'a'
char c = test2[0]; // first item in array pointed to by test2; c will now contain 'a'
char d = *test2; // alternative to fetch what is pointed to by test2; d also now contains 'a'
To make it easier to detect these sort of faults, perhaps I'll make the fault handlers throw the mbed BLOD by default :)
Simon
Hi
I'm using the strcpy function. My code compiles fine, but then the MBED crashes. No siren lights, it just stops.
Probably just a stupid c mistake on my behalf? Any guidance appreciated.
Thanks