9 years, 6 months ago.

sprintf stops execution

When I use sprintf in my programs the bed stops executing from that line onwards. Here is a simple example:

#include "mbed.h"

int main() {
    char *images_dir;
    char *sd_dirent = "101_PANA";
    char *dir_to_scan = "/sd/DCIM";
    
    printf("Executing test:\r\n");
    printf("%s/%s\r\n", dir_to_scan, sd_dirent);
    sprintf(images_dir, "%s/%s", dir_to_scan, sd_dirent);
    printf("%s\r\n", images_dir);
    printf("Done!\r\n");
}

When I attach to the serial output of the bed over USB and restart it I see:

Executing test:
/sd/DCIM/101_PANA

From this it seems to me that sprintf is failing; the same thing happens with strcpy and strcat - does anyone know what's going on and how I can use sprintf?

1 Answer

9 years, 6 months ago.

Your variable images_dir is not initialized to point to any memory so when sprintf tries write to the memory it fails and the program is halted. The simplest solution is to change the declaration of images_dir to be a char array:

char images_dir[256];

Accepted Answer

And in order to play safe consider using snprintf(images_dir,256,....)

sprintf has no idea how much space it has to output data to, it will keep writing until it's output the full string even if this means overflowing the buffer and causing your program to crash.

snprintf limits the output to the given size.

If due to the formatting you are using you know that your buffer will always be large enough then this is redundant however if there is any risk at all of overflow then it's well worth the minimal extra overhead to use snprintf and add the extra protection.

posted by Andy A 29 Apr 2015