又一次, 见到返回栈指针, 好吧, 我们从错误中来学习一下。 为了简便起见, 我简化一下原来的程序:

#include <stdio.h>
#define MAX_URL_LEN 1024

void fun(char *pOut, int size)
{
	char str[] = "abc";
	pOut[size - 1] = '\0';
}

int main()
{
	char szOut[MAX_URL_LEN + 1] = {0};
	fun(szOut, sizeof(szOut));

	printf("%s\n", szOut);

	return 0;
}

      首先, 这程序的风格还是不错的, 知道用宏来避免魔鬼数字, 知道变量要初始化, 知道fun的出参需要带一个size. 但是, 上面程序是有问题的。pOut一旦fun结束后, pOut中就是垃圾值了。 

       改为下面的吧:

#include <stdio.h>
#include <string.h>
#define MAX_URL_LEN 1024

void fun(char *pOut, int size)
{
	char str[] = "abc";
	strncpy(pOut, str, size - 1);
	pOut[size - 1] = '\0';
}

int main()
{
	char szOut[MAX_URL_LEN + 1] = {0};
	fun(szOut, sizeof(szOut));
	printf("%s\n", szOut);

	return 0;
}





本文转载:CSDN博客