Reputation: 1434
There seems to be some weirdness with snprintf
implementation in Pebble Sdk 2.x
I modified the example program to show a click counter. The following code works, if I use str[1000] size
selectCount ++;
char str[1000], buf[100];
snprintf(str, 1000, "Click %d foo", selectCount);
snprintf(buf, 100, "s(%d) one two l(%d)", sizeof(str), strlen(str) );
if(selectCount % 2)
text_layer_set_text(text_layer, buf );
else
text_layer_set_text(text_layer, str );
But if I reduce the buffer size of str to 400, the application crashes
selectCount ++;
char str[400], buf[100];
snprintf(str, 400, "Click %d foo", selectCount);
snprintf(buf, 100, "s(%d) one two l(%d)", sizeof(str), strlen(str) );
if(selectCount % 2)
text_layer_set_text(text_layer, buf );
else
text_layer_set_text(text_layer, str );
But again, if I reduce the size of str to 20, it doesn't crash. Instead it truncates buf at 7 characters; and doesn't display str at all in a text_layer.
The values in the non-crashing cases look okay when I perform
APP_LOG(APP_LOG_LEVEL_DEBUG, str);
Any help on this is appreciated. Thanks in advance.
Upvotes: 2
Views: 374
Reputation: 2509
You're using a stack buffer, but text_layer_set_text
doesn't copy its content. When the drawing occurs, the memory doesn't exist anymore.
From the documentation:
The string is not copied, so its buffer most likely cannot be stack allocated, but is recommended to be a buffer that is long-lived, at least as long as the TextLayer is part of a visible Layer hierarchy.
Upvotes: 1