skrillac
skrillac

Reputation: 11

sprintf() program undefined return value

#include <stdio.h>
#include <stdlib.h>
//#include <wchar.h>

int main(int argc, char **argv)
{
     char *c = (char *)malloc(sizeof(char) * 30);

     if (argc < 2)
     {      
         fprintf(stderr, "%s", "argc < 2\n");
         exit(1);
     }

     sprintf(c, "sprintf() string : %s\t argc: %i", argv[1], argc);
     fprintf(stdout, "%s\n", c);
     fprintf(stdout, "%s", "Done!\n");
     free(c);

     return 0;
}

I have compiled this program on two compilers, and both produce the same run-time error. However I can't pin down this error. Did I format the string correctly in sprintf()? Is there something I forgot to account for?

I run this program with an argument of argv[1] = "Sunday"

Upvotes: 0

Views: 301

Answers (2)

Myforwik
Myforwik

Reputation: 3588

You are setting c to 30 bytes in size at the malloc.

Then in the sprintf you are writting 28 bytes, plus the argv[1] string plus argc as string. This will almost certainly be more than 30 bytes.

You need to calculate the actual size you need to malloc for c properly. Or you should use snprintf instead of sprintf, which you can use to limit the number of characters written to 30 and avoid crashing.

Upvotes: 3

M.M
M.M

Reputation: 141554

You print more than 30 chars to c. To cut off the output when this happens, instead of crashing, do:

snprintf(c, 30, "bla bla....

Upvotes: 2

Related Questions