Re: How to use Delete in right way

From: Pavel Lebedinsky (m_pll)
Date: 01/28/05


Date: Fri, 28 Jan 2005 00:42:03 -0800


"Oleg Starodumov" wrote:

>> m_psText[iRow] = new char[strlen(str)];
>> strcpy(m_psText[i],str);
>
> This code corrupts the heap, because strlen returns the number of
> characters,
> excluding the terminating null. But strcpy will copy the string plus the
> terminating null,
> thus overwriting one character after allocated buffer.
>
> It is unlikely that this is the main reason of problems in the
> application,
> but should be addressed anyway. Btw, PageHeap should miss most of such
> problems,
> but Debug CRT should report them when the object is being deleted.

To be precise, pageheap will also detect this when the block
is deleted, unless the length of the block is a multiple of 8,
in which case you should get an access violation at the time of
corruption.

You can use /unaligned parameter with pageheap to force
it to always place the block exactly at the end of a page
but this breaks most non-trivial applications because win32 heap
is documented to have 8 byte alignment, and many apps depend
on this.



Relevant Pages

  • Re: give me some tips
    ... A text stream is an ordered sequence of characters composed into ... terminating new-line character is implementation-defined. ... I don't know of any implementations that actually require the trailing ... overwritten by the next shell prompt. ...
    (comp.lang.c)
  • Re: K&R2 , exercise 7.6
    ... characters including the terminating newline. ... The second declaration says that pc is a pointer to type char and ... The %s format specifier looks for a char * ...
    (comp.lang.c)
  • Re: is such exception handling approach good?
    ... I do not quite agree that when application shuts down, all object on heap is automatically freed. ... there is no memory leak. ... Terminating a process has the following results: ... The process exit code is set. ...
    (microsoft.public.vc.language)
  • Re: Query on pointers
    ... printfwouldn't have stopped after the 7 characters "iupJter". ... The snprintf() and vsnprintffunctions will write at most size-1 ... and values (including a terminating null character that is always ... it appears that a C99 implementation would put "Jupite". ...
    (comp.lang.c)
  • Re: Bug/Gross InEfficiency in HeathFields fgetline program
    ... including the terminating null character, ... the string, seems like a reasonable requirement to me. ... It's a clue that the person who wrote that description of strncpy() ... The portion you quoted also doesn't say that null characters are ...
    (comp.lang.c)