Subj : Re: malloc() To : borland.public.cpp.borlandcpp From : Sebastian Ledesma Date : Tue Jun 22 2004 02:07 pm Jan: In current era you can use extra memory, the cost of extra memory is less than the development cicle. Why you did not declare the variables as 128 or 256 bytes long? Also if you are interesed in patch your RTL libraries check: http://personal.sirma.bg/Jogy/bcrtlfix.html Saludos Sebastian "Jan Vernimmen" escribió en el mensaje news:40d85753@newsgroups.borland.com... > Hello everybody, > > This is about an error and a lame solution. > > I've made a large program (linking 16 cpp-files + 1 RC) working under Win32, > using BC 5.02 and OWL. > The program sometimes (once a week, once a day, suddenly every hour) > corrupted, changed its character-fonts (saving data was sometimes possible at > this moment) and then stopped. > (I've started building this program in 1985 on an ATARI 520 and evolved it via > DOS and BC 3.2 until what it is now.) > Using breakpoints did not work. I've written lines to a debugfile and could > approach a suspicious part. > At this point I copied manual text-input to a buffer, better say changing text > ( say input the next char in a line) in an > > existing buffer, just like: > > //-------------------------- > > if ( strlen( szInput ) > strlen( txtBuf )) > { > free(txtBuf); > txtBuf = (char *)malloc( strlen( szInput ) + 1 ); > } > strcpy( txtBuf, szInput ); > > //-------------------------- > > Where I could I tried "realloc" instead of "free + malloc"; the results were > the same. > > So to be clear: at this point the malloc went wrong, sometimes, unpredictable. > Also points where I had to update strings due to program results, the same > happened. > > I have programmed the following working solution: > txtBuf = (char *)malloc( strlen( szInput ) + 2 ); // mind + 2!! > > Of course I changed all other malloc( strlen(...)..) in the same way. > > This is working for over 6 months now without problems! > I'll be pleased with any comment on this! > Why your comment? > With this kind of errors and solutions you can only say "The errors do not > come up anymore", but never be sure that they are gone now! > > > By the way, using malloc in a 32-bit system always gives a plural of a 4-byte > space. > When I reserve 13 bytes (malloc(13)) the result is a 16 byte room, so the same > as when I should have done malloc(16). > malloc(17) gives back the same room as malloc(20) and so on. > The lowest space that can be reserved is 12 bytes. malloc(1) up to malloc(12) > is reserving 12 bytes room netto. > malloc() itself uses 4 bytes more for internal bookkeeping. So malloc(1) is > occupying a 16 byte space. > > I have tried to use this phenomenon in order to reduce the runtime malloc's > but I stopped with this in order to reduce the causes of possible errors. > > > Also at this point any comment is welcome. > Jan. > .