0

I was wondering why the following code leads to a SIGSEGV?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void splitt(char string[255]){  

    string[1] = 'a';

}

int main (void){
    
    splitt("cut");
    
}

I thought that if I passed a pointer to a function as a parameter, I could change the content of the pointer in this function and this would also have an effect in the calling function. That's why I'm confused why this doesn't work.

Thank you in advance for any help!

sidyman
  • 43
  • 3
  • You're attempting to modify the string literal `"cut"` which is illegal. Implementations commonly store string literals in read-only memory. If you passed a string that was modifiable, e.g. `char s[] = "cut"; splitt(s);` it would work. – Nate Eldredge Jun 20 '20 at 15:53
  • It's nothing to do with it being passed to a function, by the way; doing `char *p = "cut"; p[1] = 'a';` in the same function would behave the same. – Nate Eldredge Jun 20 '20 at 15:55
  • @Nate Eldredge Thanks a lot. That makes it clear for me. – sidyman Jun 20 '20 at 16:41
  • @Adrian Mole thanks for the link. Along with the answers I understand it now. – sidyman Jun 20 '20 at 16:42
  • You should accept the proposed duplicate (if you still see the blue box asking you). Your question will likely be "Closed by Vote" otherwise, and it looks better if you make the call. – Adrian Mole Jun 20 '20 at 16:44
  • To be clear, `string[1] = 'a';` does not modify the content of a pointer. – user253751 Jun 20 '20 at 19:48

2 Answers2

0

"cut" is a string literal. Changing it leads to Undefined Behaviour. Undefined Behaviour can include a SIGSEGV.

You could instead use an array.

char cut[4] = "cut";
splitt(cut);

Alternatively, you could use malloc to allocate some memory.

char* cut;
if (cut = malloc(4)) {
     strcpy(cut, "cut");
     splitt(cut);
}
gmatht
  • 835
  • 6
  • 14
0

You can refer to my answer where I talk about string literals. But long story short, the values like "string" are known as string literals and are present in the read-only memory of the executable (process); you can't modify them. Instead, you can do something like this:

splitt(strdup("cut"));

But it makes more sense to save the changes you do in the splitt() function.

So you might be wanting to have your code like this:

char* string = strdup("cut"); 

splitt(string);
m0hithreddy
  • 1,752
  • 1
  • 10
  • 17