[완료] substr 함수 질문입니다.(malloc으로 생성된 메모리 해제에 관한 질문)

ironiris의 이미지

안녕하세요~

아래처럼 간단하게 substr 함수를 만들었습니다.
그런데 코드에 이상한 점이 있어서 질문을 드립니다.(원하는 작동은 합니다만..)

어떤 문제냐면 strndup 함수 man 페이지를 보면 strndup 함수는 생성된 문자열을 리턴시키는데
이것은 malloc으로 생성되었으니까 free로 해제를 해줘야 한다고 합니다.

하지만 substr 함수에서는 새로운 문자열을 리턴해야 하기 때문에 생성된 문자열을 해제하지 않습니다.
그러면 substr를 사용하는 함수에서(여기서는 main함수)
substr로 리턴받은 문자열을 어떤 변수로 저장하지 않고 바로 printf 로 사용하고 있습니다.
이렇게 된다면 free로 해제시킬 방법이 없어보이는데...

substr에서 리턴한 문자열을 바로 사용하지 말고 변수로 받은후에 사용후 free시켜야 하는 것이 올바른 방법인가요?
그냥 printf에서 사용하는 것은 안좋은 방법인가요?

도움말씀부탁드리겠습니다.

#include <stdio.h>
#include <string.h>
 
char *substr(char *src,int start, int length);
 
int main(void){
    char *src;
    src = (char *)malloc(20*sizeof(char));
    sprintf(src,"test test");
    <span>printf("%s\n",substr(src,1,5));</span>
    free(src);
}
 
char *substr(char *src,int begin, int length){
    if (src == 0 || strlen(src) == 0 || strlen(src) < begin || strlen(src) < (begin+length)) return 0;
    return strndup(src+begin,length);
}
chadr의 이미지

좋고 안좋은 방법이라기 보다는 할당한건 반드시 해제를 해주셔야합니다.
안해주셔도 상관은 없으나..

안해주시면 메모리가 해제되지 않고 남아있기 때문에 오랫동안 작동하는 프로그램의
경우에는 메모리가 부족해지게 됩니다.

이렇게 되면 프로그램이 이유없이 죽게 되는 원인이 됩니다.

고민할 필요도 없습니다. 단순히 이것만 반드시 기억하고 계시면 됩니다.

"할당한건 반드시 해제한다"
-------------------------------------------------------------------------------
It's better to appear stupid and ask question than to be silent and remain stupid.

-------------------------------------------------------------------------------
It's better to appear stupid and ask question than to be silent and remain stupid.

ironiris의 이미지

그럼 바로 받아서 쓰면 안되겠네요. 변수로 받아서 사용하고 해제하는 코드로 바꿔야겠습니다.
감사합니다.

댓글 달기

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