Re: malloc modifying a passed string
- From: "Chris Hulbert" <cchgroupmail@xxxxxxxxx>
- Date: 28 Jul 2005 03:52:36 -0700
Scott Taylor wrote:
> 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
Since in some_func you don't use ptr in your example, it's not being
modified by malloc. I would look for memory problems elsewhere. As
far as *(ptr+4), that's outside of your allocated space.
.
- Follow-Ups:
- Re: malloc modifying a passed string
- From: Sarin
- Re: malloc modifying a passed string
- References:
- malloc modifying a passed string
- From: Scott Taylor
- malloc modifying a passed string
- Prev by Date: Re: Use of 'extern' keyword
- Next by Date: Re: malloc modifying a passed string
- Previous by thread: malloc modifying a passed string
- Next by thread: Re: malloc modifying a passed string
- Index(es):
Relevant Pages
|