C, memory allocation for a string

I am getting Bus error: 10 (on run time) just by running the following code:

char *x;
char *y = "the quick";
sprintf(x, "%s brown fox jumps over the lazy dog", y);

Looking around i have seen a few posts, and the problem seems to be that I am trying to modify a string literal, but in the above code, I think, I am not. Also, if i try to allocate some memory to x using malloc everything works, also if I allocate less memory than the one needed to store the whole string, it works even if I allocate 0.

char *x = malloc(0);
char *y = "the quick";
sprintf(x, "%s brown fox jumps over the lazy dog", y);
printf("%s\n", x); // the quick brown fox jumps over the lazy dog

Also I understand this is somehow related to memory allocation, but i'd like to specify x without telling the compiler how much memory it will take, since y may be a veeeeery long string, or even a number...



Read more here: https://stackoverflow.com/questions/67396449/c-memory-allocation-for-a-string

Content Attribution

This content was originally published by Giuppox at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: