593 Subj : Re: malloc() To : borland.public.cpp.borlandcpp From : Bob Gonder Date : Thu Jun 24 2004 01:15 pm Jan Vernimmen wrote: > if ( more characters then strlen(b) ) > { > free(b) > b=malloc() //I must check malloc, -> b=null > } > copy stuff.str to b >Do not forget the main discussion: >I had: > txtBuf = (char *)malloc( strlen( szInput ) + 1 ); // with problems >now and then > >I made > txtBuf = (char *)malloc( strlen( szInput ) + 2 ); // no problems in >the last 6 month > >In the last case malloc() seems to work fine! >To my opinion malloc is working but for unknow reasons in the first >construction it takes the wrong size. I think the problem may have had to do with the way you determined if the buffer was too small. Consider this chain of events: b = malloc(100); *b=0; if( strlen(b)/*0*/ < strlen(newstring)/*20*/ ) b=malloc( strlen(newstring)+1) if(strlen(b)/*20*/ < strlen(newstring)/*5*/) if( strlen(b)/*5*/ < strlen(newstring)/*30*/) b=malloc( strlen(newstring)+1) Just way too wasteful. Instead, I might add an int. int LenBuf = 100; b = calloc(LenBuf); if( LenBuf-1 < strlen(newstring)/*120*/ ) /* Borland specific? mem manager optimize*/ LenBuf = (((strlen(newstring)+1+4)+15)&~15)-4; b=malloc( LenBuf) . 0