함수에서 동적메모리 할당시 free?

김영호@Facebook의 이미지

#include <stdio.h>
#include <stdlib.h>
char* get_word();
int main(void)
{
	char *p;
	p=get_word();
	printf("동적 메모리에 저장된 단어는 %s입니다.\n",p);
	free(p);
	return 0;
}
char* get_word()
{
	char *s;
	s=(char*)malloc(sizeof(char)*50);
	if(s==NULL)
	{
		printf("메모리할당오류\n");
		exit(1);
	}
	printf("단어를 입력하세요: ");
	gets(s);
	return s;
}

소스코드인데요 제가 동적메모리 할당을 하면 무조건 free를 해줘야한다고 배웠는데요 만약에
아레 get_word() 함수에서 s를 free 해버리면 리턴을 못하잖아요?? 이럴땐 어떻게 하죠??
혹시몰라서 메인함수에서 p=get_word(); 니까 p를 free 해봤는데 이게 맞는지아닌지도 모르겠고,,
궁금하네요.

즉 함수에서 할당한 동적메모리의 free는 어떻게 해야하나?? (해야하나 안해도되나? 해야한다면 어떻게하나?)
이게궁금합니다.

음의 이미지

그러면 좋다는 것이겠지요. C code 로 된 오픈소스들만 찾아봐도 꼭 그렇지 않다는 것을 알 수 있을거에요.

김정균의 이미지

free를 해야 하는 것이 일단은 맞습니다. 다만 위의 코드에서는 process가 종료 되면서 memory를 반환하기 때문에 문제가 되지는 않습니다. 종료를 하지 않고 계속 get_word가 실행 된다면 leak이 발생하게 됩니다.

함수 안에서 allocate된 point를 반환 한다면, 해당 함수를 호출한 point 변수를 free 시켜 주시면 됩니다. 즉, 위의 코드는 제대로 작성 하셨다는 얘기입니다.

raymundo의 이미지

malloc 한 함수와 free 하는 함수가 서로 다른 게 눈에 거슬린다면 (실제로 거슬리는 것도 사실이고)
호출하는 함수 쪽에서 malloc 을 하고 그 주소를 넘겨주셔도 되고요. (string 관련 함수들이 많이들 그러듯이)

main() {
    char *p = malloc(...);
    get_word( p );
    free(p);
}
 
void get_word( char *p ) {
   gets(p);
}

좋은 하루 되세요!

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.