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"

5
  • 1
    Don't cast malloc: stackoverflow.com/questions/605845/… Commented May 23, 2014 at 1:06
  • What runtime error are you getting? Commented May 23, 2014 at 1:07
  • *** Process returned -1073741819 *** Commented May 23, 2014 at 1:08
  • You've only allocated 30 bytes. You're trying to put 35 characters into it. Commented May 23, 2014 at 1:09
  • Thanks! I just now counted the characters Commented May 23, 2014 at 1:11

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.