As Baldrick mentioned, you're passing a (pointer to) string constant to swapExtension
, you then pass that string constant to strchr
which in turn returns a part of that same string constant. Then with strncpy
you write to the string constant which is undefined behaviour and in your case segfaults.
Use a string (character) array instead:
char myFile[] = "myFile.c";
swapExtension(myFile, "o");
Now temp
in swapExtension
will write to the myFile
array which is valid. Though, be aware that this will only work when the length of the extensions is the same, otherwise there won't be enough space in the array. To prevent this, use:
char myFile[50] = "myFile.c";
The array will initially contain the same string but will also have space for a longer one.
See also: What is the difference between char s[]
and char * s
in C