strcpy crashes MBED?

21 Mar 2010 . Edited: 21 Mar 2010

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

 

#include "mbed.h"

DigitalOut myled(LED1);
char * test;
 
int main() {

strcpy(test,"test");

    while(1) {
        myled = 1;
        wait(0.2);
        myled = 0;
        wait(0.2);
    }
}
21 Mar 2010

Hi Mat,

char * test;

This is a pointer not an array.  It is hard to say where it points but if you insteaad write

char test[5];  // note \0 needs space as well

MBED shouldn't crash

Anders

21 Mar 2010

Hi Anders

Yep - have just worked this out on my own.

But that then means that I have to give my string a pre-set length? Is there a better way to do this?

All I am trying to do is

stringa = stringb

But in c it's all a bit fiddly.

Thanks

Mat

21 Mar 2010 . Edited: 21 Mar 2010

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

21 Mar 2010

Duh. Of course. That's very clear now. Am desperately trying to remember all of this from when I last used it about 15 years ago!

Great.

Thanks for your help.