About strcpy and memory on Arduino

丶灬走出姿态 提交于 2020-05-14 08:46:49

问题


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 how strcpy 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.


回答1:


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 (e.g., variables) and some from flash (e.g., double-quoted string constants). This saves RAM (lots!) and processing time (no copies or concatenations).



来源:https://stackoverflow.com/questions/44488382/about-strcpy-and-memory-on-arduino

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!