0

I tried the following code with sprintf, but it crashes in some cases and works fine in the other. Could anyone explain it to me?

#include <stdio.h>
#include <stdlib.h>
int main()
{
       //char *s = malloc(20); //works fine
       //char *s = "";         //does not work, no matter what the initial value is
       char s[20];       //works fine
       sprintf(s, "%s", "hello world");
       printf("%s",s);
       return 0;
}
Bence Kaulics
  • 7,066
  • 7
  • 33
  • 63
Nguyen
  • 25
  • 3

1 Answers1

3

When you are doing this:

char *s = "";

or

char *s = "longer string";

You are creating a literal string which is possibly placed in read-only memory. So you cannot change it later.

If you try to do the following syntax:

char s[] = "...";

the array will be initialized with the literal string and you will be able to modify the original array later.

Suggested questions on site:

  1. What is the difference between char s[] and char *s in C?
  2. Why do I get a segmentation fault when writing to a string initialized with “char *s” but not “char s[]”?
Community
  • 1
  • 1
Bence Kaulics
  • 7,066
  • 7
  • 33
  • 63