This is a result of passing the variable s
to morseEncode
(which presumably modifies it) as modifying s
is undefined behaviour. Specifically, modifying a string literal in such a manner is undefined behaviour per 6.4.5p6 [from C99:TC3]
It is unspecified whether these (string literal) arrays are distinct provided their
elements have the appropriate values. If the program attempts to
modify such an array, the behavior is undefined.
(text in parentheses added by me)
You might also want to take a look at this question.
You could instead declare s
like so (with automatic storage duration).
char s[] = "Hello";
If you need s
to be a pointer you could try
// Yes, sizeof(char) will always be 1 and you could remove it.
char *s = malloc(sizeof(char) * (strlen("Hello") + 1));
strcpy(s, "Hello");
// Your code that uses s here
free(s) // Important!
As an additional note @kaylum has pointed out that the original answer didn't provide a justification as to why calling the function in the two different ways produced different results. This is because the undefined behaviour you're running into just so happened to be undefined in a different way for each call. If I write out a similar program and compile it using gcc
(with no flags) I end up running into a segfault both ways; on the other hand, compiling with clang -O
both work! Its simply a product of whatever segment(s) of memory your specific compiler has decided you place each of those sequences of characters.