malloc modifying a passed string
- From: Scott Taylor <scott@xxxxxxxxxxxxxxxx>
- Date: Thu, 28 Jul 2005 10:21:20 GMT
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 .
- Follow-Ups:
- Re: malloc modifying a passed string
- From: CBFalconer
- Re: malloc modifying a passed string
- From: Grumble
- Re: malloc modifying a passed string
- From: Chris Hulbert
- Re: malloc modifying a passed string
- Prev by Date: Use of 'extern' keyword
- Next by Date: Re: Should function argument be changed in function body?
- Previous by thread: Use of 'extern' keyword
- Next by thread: Re: malloc modifying a passed string
- Index(es):
Relevant Pages
|