69,382
社区成员
发帖
与我相关
我的任务
分享
#include <stdlib.h>
void main( void )
{
int *p = ( int * ) malloc( sizeof( int ) );
if ( NULL == p )
exit( -1 );
int *q = ( int * ) malloc( sizeof( int ) );
if ( NULL == q )
{
free( p ); /*释放已经分配成功的p对应的内存空间*/
exit( -2 );
}
int *r = ( int * ) malloc( sizeof( int ) );
if ( NULL == r )
{
free( p );
free( q ); /*释放已经分配成功的p,q对应的内存空间*/
exit( -3 );
}
/*other code lines*/
free( p );
free( q );
free( r );
return;
}
typedef struct tagContext {
int *p;
int *q;
int *r;
}Context;
void initContext(Context *pContext) {
pContext->p = NULL;
pContext->q = NULL;
pContext->r = NULL;
}
void freeContext(Context *pContext) {
free(pContext->p);
free(pContext->q);
free(pContext->r);
}
// 把原先的函数修改成使用 Context
int mainProc(Context *pContext, ...)
{
pContext->p = (int *)malloc(xxx);
if (pContext->p == NULL)
return -1;
pContext->q = (int *)malloc(xxx);
if (pContext->q == NULL)
return -1;
pContext->r = (int *)malloc(xxx);
if (pContext->r == NULL)
return -1;
...
}
int main(...)
{
Context context;
initContext(&context);
int nRes = mainProc(&context, xxx);
freeContext(&context);
return nRes;
}
int main(xxx)
{
int nRes = -1;
int *p = NULL;
int *q = NULL;
int *r = NULL;
do{
p = (int *)malloc(xxx);
if (p == NULL)
break;
q = (int *)malloc(xxx);
if (q == NULL)
break;
r = (int *)malloc(xxx);
if (r == NULL)
break;
...;
}while(0);
free(p);
free(q);
free(r);
return nRes;
}
#include <stdio.h>
#include <stdlib.h>
/* 指针栈 */
enum {MAX_PTR = 100};
int *ptr_stack[MAX_PTR] = {0};
int top = -1;
/* 栈的操作 */
#define POP() ptr_stack[top--]
#define PUSH(ptr) ptr_stack[++top] = ptr
#define EMPTY() (top < 0)
int exit_code(int code);
int main(int argc, char **argv)
{
int *p = NULL, *q = NULL, *r = NULL;
if (NULL == (p = (int *)malloc(10)))
return exit_code(-1);
PUSH(p);
if (NULL == (q = (int *)malloc(20)))
return exit_code(-2);
PUSH(q);
if (NULL == (r = (int *)malloc(30)))
return exit_code(-3);
PUSH(r);
/* 做自己该做的事情 */
/* 结束 */
printf("OK\n");
return exit_code(0);
}
int exit_code(int code)
{
while (!EMPTY())
free(POP());
return code;
}
#include <stdio.h>
#include <stdlib.h>
/* 释放内存 */
#define SAFE_FREE(p_buf) \
do \
{ \
free((p_buf)); \
(p_buf) = NULL; \
} while (0)
int main(int argc, char **argv)
{
int *p, *q, *r;
int exit_code = 0;
/* 初始化为NULL */
p = q = r = NULL;
if (NULL == (p = (int *)malloc(10)))
{
exit_code = -1;
goto end_proc;
}
if (NULL == (q = (int *)malloc(20)))
{
exit_code = -2;
goto end_proc;
}
if (NULL == (r = (int *)malloc(30)))
{
exit_code = -3;
goto end_proc;
}
/* 分配成功,做自己该做的事 */
/* 如果其中有释放空间的代码,请使用SAFE_FREE() */
SAFE_FREE(q);
/* 清理并返回 */
end_proc:
SAFE_FREE(r);
SAFE_FREE(q);
SAFE_FREE(p);
return exit_code;
}