Re: bizarre malloc problem
- From: "Snis Pilbor" <snispilbor@xxxxxxxxx>
- Date: 28 Jun 2005 18:18:09 -0700
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
.
- Follow-Ups:
- Re: bizarre malloc problem
- From: CBFalconer
- Re: bizarre malloc problem
- From: Clark S . Cox III
- Re: bizarre malloc problem
- References:
- bizarre malloc problem
- From: Snis Pilbor
- Re: bizarre malloc problem
- From: Flash Gordon
- bizarre malloc problem
- Prev by Date: Re: convert int to char
- Next by Date: Aliasing/Torek's strtod() experience
- Previous by thread: Re: bizarre malloc problem
- Next by thread: Re: bizarre malloc problem
- Index(es):
Relevant Pages
|
Loading