Re: malloc modifying a passed string



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.

.



Relevant Pages

  • Re: DRAM data persistence
    ... int main(int argc, char **argv) ... char *ptr; ... However, in both cases (malloc and automatic variables), ...
    (sci.electronics.design)
  • malloc modifying a passed string
    ... char *ptr; ... even printing out mallocmodifies 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. ...
    (comp.lang.c)
  • Re: pointers
    ... I am new to strcpy and I've never used malloc. ... I guess my question is about the p as a pointer to a char. ... One book I would definitely recommend is K&R2 (full reference in the bibliography of the comp.lang.c FAQ). ...
    (comp.lang.c)
  • [PATCH 13/16] add per_cpu_dyn_array for arch percpu support
    ... char *ptr; ... More majordomo info at http://vger.kernel.org/majordomo-info.html ... Please read the FAQ at http://www.tux.org/lkml/ ...
    (Linux-Kernel)
  • -v compiler switch in gcc 4.3.0
    ... char *safegets ... char *ptr; ... char *ptr1, *ptr2; ...
    (comp.lang.c)