简体   繁体   中英

About strcpy and memory on Arduino

I'm running this code on my Arduino Uno :

#include <stdlib.h>


#include <Arduino.h>
#include <SoftwareSerial.h>
#include <MemoryFree.h>


void setup() {
  Serial.begin(9600);
  char cc[300];
  char* ce = "Bonjour ca va et toi ?Bonjour ca va et toi ?Bonjour ca va et toi ?Bonjour ca va et toi ?";
  strcpy(cc, ce, 300);
  Serial.println(getFreeMemory());
}

void loop() {
  // Put your main code here, to run repeatedly:

}

So I wanted to see how much memory this was taking. And I was surprised that it was not 300 as I expected, but 300 + len(cc). I think I don't understand howstrcpy works. But I thought this code would copy ce into cc and wouldn't use more memory.

Another thing: When I run the code without the strcpy it's like nothing was in my SRAM.

The part you're missing is that double-quoted string constants use both flash memory (program size) and RAM. It's not because of strcpy ; it's an artifact of the different types of memory on this Harvard Architecture MCU.

To avoid using both flash and RAM for string constants, use the F macro to force it to be accessible from flash ONLY:

void setup() {
  Serial.begin(9600);
  char cc[300];
  strcpy_P(cc, (const char *) F("Bonjour ca va et toi ?Bonjour ca va et toi ?"
                                "Bonjour ca va et toi ?Bonjour ca va et toi ?") );
  Serial.println(getFreeMemory());
}

... or define it as a PROGMEM character array:

const char ce[] PROGMEM =
        "Bonjour ca va et toi ?Bonjour ca va et toi ?"
        "Bonjour ca va et toi ?Bonjour ca va et toi ?";

void setup() {
  Serial.begin(9600);
  char cc[300];
  strcpy_P(cc,ce);
  Serial.println(getFreeMemory());
}

NOTES:

  • you have to use the strcpy_P variant to copy from flash, not RAM.
  • long double-quoted strings can be broken up into several adjacent double-quoted strings. The compiler will concatenate them for you.

UPDATE:

You may not need one big array if you can do your "thing" with the pieces. For example, don't make one big array so you can print or send it. Just print or send the individual pieces -- some pieces from RAM (eg, variables) and some from flash (eg, double-quoted string constants). This saves RAM (lots!) and processing time (no copies or concatenations).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM