0

NOTE: THIS QUESTION TURNS OUT TO ALREADY BE ANSWERED HERE → Is it possible to modify a string of char in C?

Assume we want to create side effects this way:

void sideEffect(char *str) {
  str++;
  *str = 'X';
}

Why are side effects on dynamically allocated memory allowed through functions?:

int main(int argc, char **argv) {
  char *test = malloc(4 * sizeof(char));
  strcpy(test, "abc");
  printf("before: %s\n", test); // before: abc
  sideEffect(test);
  printf("after: %s\n", test); // after: aXc
  free(test);
}

And why are side effects on statically allocated memory not allowed through functions?:

int main(int argc, char **argv) {
  char *test = "abc";
  printf("before: %s\n", test); // before: abc
  sideEffect(test); // creates segmentation fault :(
  printf("after: %s\n", test);
}
sueszli
  • 97
  • 9

1 Answers1

2

Why are side effects on given arguments only possible if they are dynamically allocated in C?

No, you can modify the object (including char arrays) passed by a pointer to the function. It does not matter how those objects were created or allocated.

In your example the problem is:

char *test = "ABC";

test references string literal "ABC" and string literals cannot be modified in C language (more precisely it is an Undefined Behaviour). Change to char test[] = "abc";

int main(int argc, char **argv) {
  char test[] = "abc";
  printf("before: %s\n", test); 
  sideEffect(test); 
  printf("after: %s\n", test);
}
0___________
  • 60,014
  • 4
  • 34
  • 74