malloc에서...

swhong의 이미지

#include <stdio.h>
#define MAX 1024

main()
{
    char    string[MAX];
    char    *dynstring;
    int     i,j;

    for (i = 0; i < MAX; i++)
        string[i] = '\0';

    for (i = 0; i < MAX; i++)
    {
        j = getchar();
        if (j == EOF)
            break;
        string[i] = (char)j;
    }

    dynstring = (char *)malloc(1);   // 요부분....

    strcpy(dynstring, string);

    printf("\nYour text was: %s\n", dynstring);

    free(dynstring);
}

왜 저것이 수행이 되는지요....컥....!

lantelt의 이미지

그 다음 줄에 보면 스트링카피가 일어나고 있습니다.
이 코드에서 보면 위에서 캐릭터 포인터형 하나만 선언해 주었지, 카피할 공간을 할당받은 적은 없습니다.
그래서 malloc을 이용하여 그 공간을 할당해 주고 있는듯 싶습니다.

ihavnoid의 이미지

malloc( 1 ) 이 아니라, malloc( strlen( string )+1 ) 이쯤으로 해야겠군요....

즉, dynstring에 string을 복사할만한 공간 +1 (null terminate)을 할당받아야 복사가 될테니깐요....

Consider the ravens: for they neither sow nor reap; which neither have storehouse nor barn; and God feedeth them: how much more are ye better than the fowls?
Luke 12:24

송지석의 이미지

malloc에서 할당 받은 메모리의 뒤가 비어있을 수 있습니다.

메모리가 넉넉치 못해서 malloc이 힘겹게 돌아가고 있는 상황이라면 세그먼트 폴트가 나겠지요 ;-)

카피하는 스트링의 크기를 무지막지하게 크게 해보세요.

아마 분명히 오류가 날겁니다. :wink:

malloc의 소스를 분석해본 적이 없어서 확실히는 모르겠지만 malloc에다 원하는 바이트수를 요청한다고 해서 꼭 그만큼만 할당해서 주는 게 아니라 메모리 청크의 테이블을 두고 요청한 만큼의 크기와 비슷한 만큼의 청크를 할당해주는 것으로 알고 있습니다.

unipro의 이미지

동적으로 할당된 메모리를 사용하는 C 프로그램의 가장 흔한 문제의 하나는 할당된 블럭으 마지막을 지나서 기록하는 것이다. 이런 경우에 프로그램이 즉시 종료하지 않을 수 있고, 여러문은 아마도 malloc 라이브러리 루틴에 의해 내부적으로 사용되는 일부 데이터를 겹쳐 쓸 수 있다.

그렇지만 무한정 메모리를 남용할 수는 없다. 메모리 남용이 나머지 시스템에 영향을 주기전에 이 프로그램은 종료될 것이다.

(Beginning Linux Programming, 정보문화사 중에서)

내 블로그: http://unipro.tistory.com

swhong의 이미지

고수님들 항상 감사합니다. :D

- by swhong in jgdr.net -

댓글 달기

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