Skip to content

Instantly share code, notes, and snippets.

Created July 22, 2012 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/3160604 to your computer and use it in GitHub Desktop.
Save anonymous/3160604 to your computer and use it in GitHub Desktop.
#define MYBUFFER_SIZE 64
char *mybuffer;
void setup()
{
SerialUSB.begin();
mybuffer = malloc(MYBUFFER_SIZE); // Allocate a MYBUFFER_SIZE-byte buffer for global use.
}
void loop()
{
// strGenMethod1 will allocate space for a 16-byte string, fill it with text and return a pointer to it.
char *method1 = strGenMethod1();
if(method1 != NULL) // malloc can return NULL if it's unable to allocate the required memory.
{
SerialUSB.println(method1);
free(method1); // If you don't free the memory, once loop() finishes you'll have a 16-byte memory leak.
// If you don't free the memory, on the ~1281st loop malloc will fail because all 20kB of RAM were allocated,
// and the MCU still thinks they're in use.
}
// strGenMethod2 will zero-out the entire buffer, and wrote your string to it.
strGenMethod2(mybuffer, MYBUFFER_SIZE);
SerialUSB.println(mybuffer);
// Because it's a global buffer that is re-used, you don't need to worry about releasing the memory back.
// This is the generally preferred method of getting the job done.
SerialUSB.println("This is OK!!");
}
char *strGenMethod1()
{
char *buff = malloc(16);
if(buff == NULL) return NULL;
sprintf(buff, "This is Wrong!!");
return buff;
}
void strGenMethod2(char *buff, int n)
{
// Using memset on the entire length of the buffer is expensive and time consuming.
// You may not need to do it, since "a string" is always \0 terminated.
memset(buff, '0', n);
sprintf(buff, "This is wrong!!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment