[comp.sys.ibm.pc] MSC5.1: bug in realloc

pyt@hprnd.HP.COM (Pierre-Yves Thoulon) (11/01/88)

I've recently had trouble with the realloc function in the Microsoft C
v5.1 small model run-time library: for a reason yet unknown to me, it
hangs, being caught in an infinite loop (I could track it down to the
assembly language level with CodeView).

Below is a small program that is guaranteed to catch the problem.
What it does is basically the following:

	* allocate space for an array of 24 byte structures
	* copy some stuff (garbage actually...) to the allocated space
	* reallocate a larger space for the same array (24 more bytes)
	* copy some stuff to the newly allocated space
	* etc...

For whatever reason the pointer returned by realloc changes every time
realloc is called. After something like 5 to 10 iterations, realloc 
hangs. Alt-Ctl-Del is the only means of getting things back into control.

Has anyone seen this problem ? Does anybody have a working realloc function ?
Or am I missing something (I'm new to MSC and the realloc function...) ?
Any help appreciated.

Thanks,
Pierre-Yves THOULON.

-----------------------------cut here-----------------------------------
#include <dos.h>
#include <malloc.h>
#include <stdio.h>
#include <string.h>

struct FileInfo 
{
    char Dummy0; /* so that the unsigned be correctly aligned on
            a word boudary */
    char Attrib;
    unsigned WrTime;
    unsigned WrDate;
    long Size;
    char Name[13];
    char Dummy1; /* so that the next structure in the array be
            correctly aligned on a word boundary */
};

void GetFileList(void)
{
    struct FileInfo *Files;
    struct find_t DosReturn;
    int FileNum = 0;
    
        Files=NULL;
        for(;;)
        {
            printf("FileNum = %4d, Files = %5u\n",FileNum,Files);

            /*
             * [Re]allocate space for the structure array.
	     * Below is the faulty realloc that hangs (sometimes...)
	     * I know it's not really efficient to allocate 24 bytes at
	     * a time, but that's the best way to have it hang...
	     */
            if ((Files = (struct FileInfo *)realloc(Files,(FileNum + 1) * sizeof(struct FileInfo))) == NULL)
            {
                printf("Cannot reallocate memory");
                exit(-1);
            }
            
            /*
             * Copy the (uninitialized...) DosReturn structure to the
	     * newly allocated space
             */
            memcpy(&Files[FileNum++].Attrib,&DosReturn.attrib,sizeof(struct FileInfo));
        }
}


/**********************************************************************
 *
 *  Function : main
 *
 **********************************************************************/
 
main()
{
        GetFileList();
}