Memory Leak이 이 경우 발생할까염?

익명 사용자의 이미지

#include

typedef struct
{
char strName[20];
int iAge;
double dHeight;
} stTesterItem;

typedef struct
{
char strName[10];
int iLength;
stTesterItem *item;
} stTester;

int tester_getData(stTester *tester);

int main()
{
stTester tester;
stTesterItem item;
int i=0;

tester_getData(&tester);
printf("Global Name %s\n", tester.strName);
printf("----- item list -----\n");
for(i=0 ; i {
printf("[%02d]\n", i+1);
item = ((stTesterItem *)(tester.item))[i];
printf("Name %s\n", item.strName);
printf("Age %d\n", item.iAge);
printf("Height %lf\n", item.dHeight);
}
free(tester.item);
}

int tester_getData(stTester* tester)
{
stTesterItem *items;
int i=0;

strncpy(tester->strName, "Lists", 5);
tester->iLength = 2;
items = (stTesterItem *)malloc(sizeof(stTesterItem)*2);
for(i=0 ; i<2 ; i++)
{
strncpy(items[i].strName, "Inshik", 6);
items[i].iAge = 29 * (i+1);
items[i].dHeight = 170.2 * (i+1);
}
tester->item = items;
return 1;
}

이 경우에서여... main함수의 free부분이 없을 경우에염... 메모리 누수가 발생할까염?

답변 부탁 드립니다. 그럼 수고하세염...

익명 사용자의 이미지

당연히 동적으로 활당을 했으니 free를 해줘여겠지요...

안그러면 당여니 누수가 발생하겠지요??

익명 사용자의 이미지

그렇네염... 감사합니다.

테스트 해보니까 나네염... ~..~ 그럼 수고하세염...

어떻게 하문 main 작성을 편하게 할 수 있을까염?

익명 사용자의 이미지

라이브러리화 시켜서 함수 콜로만 하시면 편한 main이 되겠지요 ^^*

익명 사용자의 이미지

답변 감사합니다.

제가 말씀드린 거는염... 지금 현재 보시문 call된 곳에서 malloc하고
main에서 free하지 않습니까? main을 짜는 놈은 단순 무식해서 malloc,
free같은 거는 쓰고 싶지 않다는 놈이라고 생각하문여... call된 놈은 어
떤 식으로 해야 될까염... ??

미리 감사합니당...

빠빠....이

익명 사용자의 이미지

이렇게 하면 될거 같은데요..

민인식 wrote..
#include <stdio.h>

typedef struct
{
char strName[20];
int iAge;
double dHeight;
} stTesterItem;

typedef struct
{
char strName[10];
int iLength;
stTesterItem *item;
} stTester;

int tester_getData(stTester *tester);

int main()
{
stTester tester;
stTesterItem item;
int i=0;

tester_getData(&tester); // 이렇게 data를 얻는 함수가 있으면 처리 함수를 만들면 되겠지요?
// 여기서 부터 free()까지 해주는 부분을 함수로 처리하고.
// tester부분을 pointer로 넘겨주면 될거 같네여.
// 즉 아까도 말했지만 단순하게 함수콜로만 처리가 가능하겠지여 ^^*

printf("Global Name %s\n", tester.strName);
printf("----- item list -----\n");
for(i=0 ; i<tester.iLength ; i++)
{
printf("[%02d]\n", i+1);
item = ((stTesterItem *)(tester.item))[i];
printf("Name %s\n", item.strName);
printf("Age %d\n", item.iAge);
printf("Height %lf\n", item.dHeight);
}
free(tester.item);
}

int tester_getData(stTester* tester)
{
stTesterItem *items;
int i=0;

strncpy(tester->strName, "Lists", 5);
tester->iLength = 2;
items = (stTesterItem *)malloc(sizeof(stTesterItem)*2);
for(i=0 ; i<2 ; i++)
{
strncpy(items[i].strName, "Inshik", 6);
items[i].iAge = 29 * (i+1);
items[i].dHeight = 170.2 * (i+1);
}
tester->item = items;
return 1;
}

그럼 즐프 하세요...

익명 사용자의 이미지

가능한 방법들입니다.
호출하는 함수를 "main()" 이라 하고
호출되는 함수를 그냥 "함수"라고 편의상 가정합시다.

1. main()에서 공간을 잡은 후 함수를 호출한다.
공간을 잡을 때 지역변수로 하거나 malloc()을 하거나
상황에 따라 선택한다.

2. 호출되는 함수 내에서 변수를 static으로 선언한다.
해당 예로 들 수 있는 함수가 localtime(), ctime(), inet_ntoa() 등이 있
다.
장점은 main()에서 공간을 미리 잡을 필요도 없고
free()를 하지 않아도 된다는 것이지만
문제는 multi-thread에서 안전할 수 없다는 것이다.

3. 관련 데이터들을 묶어 구조체로 만든 후 초기화(공간할당)하고
해제하는 method들도 해당 구조체의 필드에 함께 넣어
main()에서 method 호출로 대신한다.
장점은 main()은 구조체의 내부 구조를 알 필요가 없다는 것이다.

ex)
typedef struct _data
{
char *buf;
int (*init)(struct _data*);
int (*release)(struct _data*);
}Data;

Data data;
data.init(&data);
data.release(&data);

(init()과 release()의 세부 내용은 설명 생략)

이상은 제가 자주 사용하는 방법들입니다만
더 멋진 방법이 또 있겠죠...
다른 분들은 어떻게들 하시나...

2번은 가급적 피해야 하고,
해당 데이터가 예로 든 구조체처럼 필드 달랑 하나짜리라면 1번이 좋을테고
다소 복잡한 경우라면 3번이 적당하리라 봅니다.

익명 사용자의 이미지

안녕하세요. 민인식입니다.

찾고있던 해답을 찾은 기분입니당... ^^..

정말 감사드리구염... ^^

행복하시길....

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.