메모리 동적 할당과 해제..
글쓴이: leolo / 작성시간: 토, 2003/05/31 - 1:10오후
다음과 같은 메모리 동적할당에서..
메모리 free는 어떻게 하나요..
현재 보시면.. new는 동적으로 할당된 cgi_object의 주소를 가지고
new->name과 new->value를 위한 동적 메모리 할당이 된 상태입니다.
이 경우 첫번째 시작 노드를 가리키는 변수가 있다면,
예를 들어 struct cgi_object *list = NULL; 이 첫번째 노드를 가리킨다면,
어떻게 메모리를 해제할까요?
아주 간단한건데도 제 생각대로 해봤는데도 메모리 누수가 생깁니다..
원 구조체..
struct cgi_object{
char *name;
char *value;
struct cgi_object *next;
};
제 생각대로 한 코드.. 문제가 있나요..
void cgi_free(struct cgi_obejct *ptr)
{
struct cgi_object *current = ptr;
struct cgi_object *next;
while(current != NULL){
next = current->next;
free(current->name);
free(current->value);
free(current);
current = next;
}
ptr = NULL;
}
static int cgi_split_pairs(char *query)
{
char *start, *mid, *end;
struct cgi_object *new;
int count=0;
start=query;
while (start!=NULL && *start!=0)
{
int len;
if ((end=strchr(start, '&'))==NULL)
end=start+strlen(start);
if ((mid=strchr(start, '='))==NULL)
mid=end;
if (mid > end) mid=end;
if (start == mid)
{
start=end+1;
continue;
}
new=(struct cgi_object *)malloc(sizeof(*new));
if(new==NULL)
exit(1);
len=mid-start;
new->name=(char *)malloc(len+1);
if(new->name==NULL)
exit(1);
url_decode(new->name, start, len);
if (end > mid)
{
mid++;
len=end-mid;
new->value=(char *)malloc(len+1);
url_decode(new->value, mid, len);
new->value[len]=0;
}else
new->value=NULL;
new->next=list;
list=new;
start=end;
if (*start=='&') start++;
count++;
}
return (count );
}
Forums:


문제가 없어 보입니다...
제 생각대로 한 코드.. 문제가 있나요..
void cgi_free(struct cgi_obejct *ptr)
{
struct cgi_object *current = ptr;
struct cgi_object *next;
while(current != NULL){
next = current->next;
free(current->name);
free(current->value);
free(current);
current = next;
}
ptr = NULL;
}
위 코드에서는 특별한 문제가 없어 보입니다.
메모리 누수가 발생한다면 해제하는 부분보다는 할당에서 지정된대로
할당이 안됐거나, 위의 리스트를 관리하는 코드에서 오류가 났을 가능성이
있을 수 있습니다. 그 부분을 점검해 보시는 것이 좋겠네염...
댓글 달기