Niels
Niels

Reputation: 306

C handling large strings without overloading the 2KB of RAM (microcontroller ATMEGA328P)

  char* largeString = malloc(sizeof(*largeString));
  largeString = "some large string with ONLY alphanumerical values and . , ' \n and at the end: \0";

   while(*largeString != '\0') {
       printf("%c", *largeString );
       ++largeString ;
   }

I need to print a large string, the problem is the string is too large, if I make the string a bit smaller everything works fine, but when the String is too big, it doesn't work.

So I tried putting the variable on the heap and printing it character after character if maybe that would help, but unfortunately not.

When running it I can see that the RAM usage is 97% (the total RAM is 2048bytes). When I remove the code from above the RAM usage drops back down to 20-30%.

I am using atmega328P.

Is there any way of printing and\or handling large strings without overloading the available RAM?

Upvotes: 0

Views: 112

Answers (1)

0___________
0___________

Reputation: 67709

  1. Forget about malloc and dynamic allocation when programming tiny uCs. Simply forget about dynamic memory allocation.

  2. To prevent string literals or another const data from consuming RAM (normally everything is copied to RAM as AVR have separate address spaces for data and code), you need to place the data into the program memory. To access this memory special assembly instructions are needed:

There are two methods:

  1. Old style PROGMEM
#include <avr/pgmspace.h>
char FlashString[] PROGMEM = "This is a string held completely in flashmemory."; 

and use special functions and macros to access this type of data : https://www.nongnu.org/avr-libc/user-manual/group__avr__pgmspace.html

  1. Newer gcc named address spaces: https://gcc.gnu.org/onlinedocs/gcc/Named-Address-Spaces.html

Upvotes: 2

Related Questions