Re: bizarre malloc problem




Flash Gordon wrote:
> Snis Pilbor wrote:
(snip)
> > I seem to be suffering the exact opposite of fragmentation: I have no
> > problem whatsoever allocation a large array of structures, but if I try
> > to allocate room for just 1 single structure, the program immediately
> > throws an exception. Debugging indicates the exception is indeed
> > thrown by malloc itself and not by some later line of code.
>
> This normally means you have corrupted the the structures used to manage
> the heap (on implementations with a heap). This is generally the result
> of either running off the end of a buffer or freeing a pointer twice.
>
(snip)

Ahh, thank you so very kindly for this insight. Knowing this, I
shifted my attention to a different part of my code and believe I was
able to find the culprit.

Old bad code:

char *str_alloc( char *string )
{
char *x = (char *) malloc( strlen(string) * sizeof(char));
strcpy(x,string);
return x;
}

Fixed code:

char *str_alloc( char *string )
{
char *x = (char *) malloc( (strlen(string)+1) * sizeof(char) );
strcpy(x,string);
return x;
}

Wow, I have learned a lot from this. One of these days I am going to
have to teach myself the intricate details of how malloc works. The
naive expectation would be to assume the strcpy in the unfixed code
above would have immediately excepted. But that would be the clumsy,
slow, inefficient Java way to do it. Thanks again for the help,
everyone who chipped in. Oh, and sorry about not posting the entire
code in my OP-- the entire code is over 2000 lines so I didn't imagine
that would have been appropriate.

Snis

.



Relevant Pages

  • Re: Analyzing this Progression
    ... 7ths of 7th chords resolve downward. ... No, it's not an exception. ... the lower member rises or falls. ...
    (rec.music.theory)
  • Re: When is a function not a function?
    ... a DOM element and Array or a value with falseness. ... assertion that the test betrays poor design. ... assume the worst case (that the exception will be thrown), ...
    (comp.lang.javascript)
  • Re: A C++ Whishlist
    ... Java is annoying enough with its exceptions to the operator overloading ... What's the point in "catching" an exception for a statement where you ... "Je ein Stueckchen Kreppsohle an die Fuesse eines Hamsters kleben. ...
    (comp.lang.cpp)
  • Re: Jon Skeets thread pooling sample
    ... that decision - I can't think of a good reason why the name of a thread has ... > 4) Add some sort of exception logging for this and the other events. ... It needs to be set before the 1st callback occurs ...
    (microsoft.public.dotnet.general)

Loading