0
#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"

Barmar
  • 669,327
  • 51
  • 454
  • 560
skrillac
  • 11
  • 1
  • 3

2 Answers2

3

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.

Myforwik
  • 3,266
  • 4
  • 34
  • 42
2

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....
M.M
  • 134,614
  • 21
  • 188
  • 335