[uClibc] FW: malloc/free memory leak in uClibc 0.9-20?

Wen Yang weny at promise.com
Thu Oct 2 00:07:34 UTC 2003


Since my original e-mail with the attachments was rejected by the uclibc
moderator (it was more than 40K), I'd post the sample source here. 

#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/fcntl.h>

#define FILE_BUFFER_SIZE	(64*1024)

void printMemoryStatus(char * pFileBuf)
{
	int fd;
	int timeSleep = 1;
	size_t szReturned = 0;
	char strFileName[256];
	pid_t pid = getpid();

	sleep(1);
	
	sprintf(strFileName, "/proc/%d/status", pid);
	fd = open(strFileName, O_RDONLY);
	if (fd != -1)
	{
		szReturned = read(fd, (void *)pFileBuf,
FILE_BUFFER_SIZE);
		if (szReturned == 0)
		{
			printf("reach the end of file\n");
		}
		else
		{
			printf("%s\n", pFileBuf);
			timeSleep = 3;
		}
		
		close(fd);
	}
	else
	{
		printf("failed to open file %s\n", strFileName);
	}
	
	sleep(timeSleep);
}

int main()
{
	unsigned char * pBuf = NULL;
	unsigned char * pBuf1 = NULL;
	unsigned int capacity = 8, capacitySave = 0;
	char * pFileBuf = NULL;

	pFileBuf = (char *)malloc(FILE_BUFFER_SIZE);
	if (pFileBuf == NULL)
	{
		printf("failed to allocate file buffer\n");
		return 1;
	}
	
	printf("before allocate loop\n");
	printMemoryStatus(pFileBuf);
	
	capacity = 8;

	pBuf = (unsigned char *)malloc(capacity);
	if (pBuf == NULL)
	{
		free(pFileBuf);
		printf("allocate memory %d failed\n", capacity);
		return 1;
	}
	printf("after allocate %d\n", capacity);
	printMemoryStatus(pFileBuf);
	
	memset(pBuf, capacity, capacity);
	
	while (capacity < (4*1024*1024))
	{
		capacitySave = capacity;
		capacity = capacity << 1;

		printf("allocating memory %d\n", capacity);
		
		pBuf1 = (unsigned char * )malloc(capacity);
		if (pBuf1 == NULL)
		{
			printf("failed to allocate memory\n");
			break;
		}
		memcpy(pBuf1, pBuf, capacitySave);
		memset((pBuf1+capacitySave), capacity, (capacity -
capacitySave));
		free(pBuf);
		pBuf = pBuf1;

		printMemoryStatus(pFileBuf);
	}

	
	free(pBuf);
	printf("after free pBuf\n");
	printMemoryStatus(pFileBuf);

	printf("after sleep for 2 second\n");
	sleep(1);
	printMemoryStatus(pFileBuf);

	printf("after sleep for 2 second\n");
	sleep(1);
	printMemoryStatus(pFileBuf);

	free(pFileBuf);

	printf("program quit\n");

	return 0;
}





More information about the uClibc mailing list