malloc modifying a passed string




I've searched through the FAQ but I can't find this problem, which seems like it should be a newbie one. Here is a following code sample, without the necessary testing of malloc, including of standard libraries, etc...


main() {
  char *ptr;
  ptr = malloc(4);
  strcpy(ptr, "abc");
  some_func(ptr);
  ...
}

void some_func(char *ptr) {
  char *ptr2;
  ptr2 = malloc(5);
  ...
}

When I get to some_func, and malloc any value (as I here did ptr2=malloc(5) ), some value of *ptr becomes modified. For instance, *(ptr+3), which was previously equally to '\0', is now equal to char value 23 ('\023'), and *(ptr+4) now is '\0'. This value isn't consistently 23. Some times it a '#' character...etc. But it always seems to be just an addition to the string of one char. Why does this happen?

When the second malloc is called in some_func, is there any reason why that the original pointer should be modified. Using a debugger (gdb), even printing out malloc(1) modifies the buffer.

If there is an easy solution I would love to hear it, or be redirected to a previous post, the FAQ, or whatever is most applicable.

Thank you in advance,

Scott Taylor
.



Relevant Pages