21. 资源使用的规范

void ErrorProc() {
	printf("用户你好,我们的系统出错了,现在要退出");
}

int main(int argc, char *argv[]) {
	//先给所有资源赋一个错误值,后面给每个资源赋正确值并验证确实正确,正确就使用,任意一个出错就调到总出口处理

	char *pszA = NULL;
	char *pszB1 = NULL;
	char *pszB2 = NULL;
	char *pszC = NULL;
	char *pszD1 = NULL;
	char *pszD2 = NULL;

	pszA = (char *)malloc(10);
	if (pszA == NULL) {
		ErrorProc();
		goto EXIT_LABEL;//相当于C++ throw
	}
	
	pszB1 = (char *)malloc(20);
	if (pszB1 == NULL) {
		ErrorProc();
		goto EXIT_LABEL;//相当于C++ throw
	}

	pszB2 = (char *)malloc(30);
	if (pszB2 == NULL) {
		ErrorProc();
		goto EXIT_LABEL;//相当于C++ throw
	}

	pszC = (char *)malloc(40);
	if (pszC == NULL) {
		ErrorProc();
		goto EXIT_LABEL;//相当于C++ throw
	}

	if (argc > 3) {
		pszD1 = (char *)malloc(50);
		if (pszD1 == NULL) {
			ErrorProc();
			goto EXIT_LABEL;//相当于C++ throw
		}
	}
	else {
		pszD2 = (char *)malloc(60);
		if (pszD2 == NULL) {
			ErrorProc();
			goto EXIT_LABEL;//相当于C++ throw
		}
	}

	//能执行到这里,说明没有发生错误,可以正常使用资源了
	strcpy(pszA, "A");
	strcpy(pszB1, "B1");
	strcpy(pszB2, "B2");
	strcpy(pszC, "C");

EXIT_LABEL://相当于C++ catch
	if (pszA) {
		free(pszA);
		pszA = NULL;//释放后将引用资源的指针或变量赋值为NULL,后续错误引用时可触发异常(杜绝野指针)
	}
	if (pszB1) {
		free(pszB1);
		pszB1 = NULL;
	}
	if (pszB2) {
		free(pszB2);
		pszB2 = NULL;
	}
	if (pszC) {
		free(pszC);
		pszC = NULL;
	}
	if (pszD1) {
		free(pszD1);
		pszD1 = NULL;
	}
	if (pszD2) {
		free(pszD2);
		pszD2 = NULL;
	}
	return 0;
}

  

posted @ 2020-05-01 07:43  八转达人  阅读(222)  评论(0编辑  收藏  举报