C realloc 實戰

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/************************************************************************/
/*  直接返回地址.                                                                     */
/*    */
/*    */
/************************************************************************/
char* getLine(void)
{
	const size_t sizeIncrement = 10;
	char *buffer = (char*)malloc(sizeIncrement);
	char *currentPosition = buffer;
	size_t maximunLength = sizeIncrement;
	size_t length = 0;
	int character;
		

	//  malloc memory  for buffer faile;
	if (NULL == buffer)
	{
		return NULL;
	}

	while (1)
	{
		character = fgetc(stdin);
		//  \n  is end input;
		if (character == '\n') 
		{
			break;
		}

		if (++length > sizeIncrement)
		{
			char *newBuffer = (char*)realloc(buffer, maximunLength += sizeIncrement);
			if (NULL == newBuffer)
			{
				free(buffer);
				return NULL;
			}
			
			// adjust currentPosition;
			currentPosition = newBuffer + (currentPosition - buffer);
			buffer = newBuffer;
		}
		*currentPosition++ = character;
	}

	*currentPosition = '\0';
	return buffer;

}



/************************************************************************/
/* 返回的是輸入的長度  */
/*   */
/************************************************************************/
size_t getLinePoint(char **buffer)
{
	const size_t sizeIncrement = 2;
	// 保留原始的地址,用於指針的計算 。
	char *pos = NULL;
	// 用於實時調整指針的位置.
	char *currentPosition = NULL;
	*buffer = pos  = currentPosition  =  (char*)malloc(sizeIncrement);
	size_t maximunLength = sizeIncrement;
	size_t length = 0;
	int character;


	//  malloc memory  for buffer faile;
	if (NULL == buffer)
	{
		return 0;
	}

	while (1)
	{
		character = fgetc(stdin);
		//  \n  is end input;
		if (character == '\n')
		{
			break;
		}

		if (++length > sizeIncrement)
		{
			char *newBuffer = (char*)realloc(*buffer, maximunLength += sizeIncrement);
			if (NULL == newBuffer)
			{
				free(buffer);
				return 0;
			}

			// adjust currentPosition;  如今的位置 - 起點位置 = 已佔用的空間.
			// 新的起點 + 已佔用空間的大小 = 新的浮動位置.
			currentPosition = newBuffer + (currentPosition - pos);

			// 從新調整地址.
			*buffer = newBuffer;
		}
	
		*currentPosition++ = character;
	}

	// 程序最關鍵的地方. 不然會出現訪問到其餘地址內的數據.
	*currentPosition = '\0';
	return length;
}




int main()
{
	char* a = NULL;
	size_t b = 0;
	//a = getLine();

	//printf("stdin is %s", a);

	b = getLinePoint(&a);
	if (b > 0)
	{
		printf("stdin is %s", a);
	}

	return 0;
}
相關文章
相關標籤/搜索