0

This code compiles with no errors under cygwin and under linux. But when i run it, it runs with no errors in cygwin but it core-dumps under linux.

can someone shed some light about the memory management of these systems that would explain why the different behaviors?

#include <stdio.h>
void foo(char *p){
 p[0]='A';
}

void main(){
  char *string ="Hello world!";
  foo(string);
  printf("%s\n", string);
}

Thanks for the answers and makes sense that behavior is not defined, however i was interested in the differences of the underlying systems that lead to these 2 distinct undefined behaviors. I imagine its related to how they manage memory but looking for someone who is familiar with the internals who can explain why one ends up crashing while the other one does not.

flx5t42
  • 19
  • 1

3 Answers3

1

In C++ string literals must not be modified. And with that pointer that's what you're trying to do.

If you want to modify it, you'll have to declare it like this:

char string[] = "Hello world!";
Daniel
  • 21,933
  • 14
  • 72
  • 101
1

Modifying char* causes undefined behaviour , just because it does not crash , does not mean it won't. That is what undefined means , the behavior is not predictable , in your case , the program not crashing is also not predictable.

Barath Ravikumar
  • 5,658
  • 3
  • 23
  • 39
0

modification of a constant string is undefined behavior.

Also please define main() as

int main(void)
{
  //your program
  return 0;
}
Aniket Inge
  • 25,375
  • 5
  • 50
  • 78