Subj : Re: malloc() To : borland.public.cpp.borlandcpp From : waking Date : Wed Jun 23 2004 10:41 pm On Wed, 23 Jun 2004 15:59:50 +0200, Jan Vernimmen wrote: >>>if ( strlen( szInput ) > strlen( txtBuf )) >> Is the buffer *guaranteed* to have a terminating nul character >I've written the strings, their length and the ASCII values to a debugfile. >I cannot find errors. That's not what I asked. You're still thinking/talking about strings. I was asking about the *buffer* and its initial state. Reread it: >>... Especially on the first iteration. i.e. - >> Is the *initial* allocation of an adequate size and zero-filled >> or zero-terminated? >> Is the buffer *guaranteed* to be at least one byte larger than >> strlen( txtBuf )? To restate the issue: Your conditional statement >if ( strlen( szInput ) > strlen( txtBuf )) presupposes that txtBuf actually *contains* a nul-terminated string. My question was/is: What is the buffer's state on the *first* iteration of this loop? How was it initialized? You *cannot* use strlen() to determine the size of the *buffer*. It can only determine the length of any string *in* the buffer. Memory allocated with malloc is uninitialized. Its contents will be random - whatever happens to be in those memory locations at the time. Therefore, you *cannot* use strlen on a buffer immediately after malloc without first setting at least one of the bytes within the buffer to nul (binary zero in this case). If you do: txtBuf = malloc(size); if ( strlen( szInput ) > strlen( txtBuf )) [snip] then the results will be totally unpredictable. If strlen does not find a nul within the random data of the buffer, it will keep looking past the end of the buffer until it finds one. The value returned by strlen will then be greater than the actual size of the buffer, creating the false impression that the buffer is big enough. Before using strlen on the buffer, it *must* be properly initialized. This can be done by using calloc instead of malloc, or by setting at least one of the bytes in the buffer to nul (e.g.- txtBuf[0] = '\0';) immediately after the malloc. >> (4) A memory leak (failure to free memory) in an iterative >> procedure has caused depletion/fragmentation of the heap, >> with the result that an allocation attempt fails. > >Can I test this? malloc() returning zero or something like that? Yes. A NULL return from malloc will indicate that the heap is exhausted or badly fragmented. CodeGuard or MemProof should help identify any such leaks by flagging unfreed memory blocks when the program terminates. >All moduls are built in the same project, now and then with "Build All" Make sure that there aren't any *local* options set for a specific module which may conflict with the *global* options used by modules which don't have local overrides. -- Wayne A. King (waking@idirect.com, Wayne_A_King@compuserve.com) .