기초 C 질문.. 함수내에서 메모리 할당(array).

MasterQ의 이미지

void foo(int num)
{
    char buf[num];
    int i;
    for (i = 0 ; i < num - 1 ; i++ ) {
        buf[i]='q';
    }
    buf[num - 1] = '\0';
    printf("%s\n", buf);
}

실행 잘되구요...

아니. buf[num]가 원래 됐었던 건가요?

이렇게 parameter로 받은 num을 언제부터 malloc쓰지 않고도

이런식으로 선언해서 쓸수 있는지 궁금합니다..

흠!! 지금 쓰는 컴팔러는 gcc 3.2입니다...

기억이 맞다면 예전에는 에러 났었던것 같거든요.....

이렇게 코드를 써도 될까 걱정이네요... 만약 옛 컴팔러에서 안된다면 피하고 싶어서요...

새로 바뀐 표준인가요? (C99)

mykldp의 이미지

cedar의 이미지

C99 표준 맞습니다. GCC 구버전 뿐만 아니라, 웬만한 상용 컴파일러에서도 아직 지원하지 않는 경우가 많습니다. 뭐 아직 C++98도 100% 완벽히 지원하는 컴파일러도 없는데요.
다른 개발 환경으로의 이식성을 생각한다면 C99 표준에만 있는 문법은 쓰지 마세요. 반면에 C++98은 웬만한 환경에선 다 된다고 보시면 됩니다.

전웅의 이미지

cedar wrote:
C99 표준 맞습니다. GCC 구버전 뿐만 아니라, 웬만한 상용 컴파일러에서도 아직 지원하지 않는 경우가 많습니다. 뭐 아직 C++98도 100% 완벽히 지원하는 컴파일러도 없는데요.

http://www.comeaucomputing.com

Quote:
This combination of Comeau and Dinkumware is as close as you can get to full compliance with Standard C++, Standard C from 1999 (aka C99) and Standard C from 1990 (aka C90).

음... 개인적인 친분은 있지만 절대 광고 목적은 아닙니다.

그럼...

--
Jun, Woong (woong at gmail.com)
http://www.woong.org

cdpark의 이미지

cedar wrote:
C99 표준 맞습니다. GCC 구버전 뿐만 아니라, 웬만한 상용 컴파일러에서도 아직 지원하지 않는 경우가 많습니다.

GCC 구버젼에서 이미 gcc 자체 확장으로 지원하던 기능입니다. 최소한 gcc 2.95에서 지원하고 있습니다.

mushim의 이미지

char buf[num];

하고

char *buf = malloc(sizoef(char)*num);

그럼 위의 두 식은 실질적으로 같은 건가요?

전웅의 이미지

mushim wrote:
char buf[num];

하고

char *buf = malloc(sizoef(char)*num);

그럼 위의 두 식은 실질적으로 같은 건가요?

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

void func(int num)
{
    char buf1[num];
    char *buf2 = malloc(num);
    assert(buf2);

    printf("%lu\n", (unsigned long) sizeof(buf1));    /* sizeof(char) * num == num */
    printf("%lu\n", (unsigned long) sizeof(buf2));    /* sizeof(char *) */
}

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

char *func1(int num)
{
    char buf[num];

    return buf;
}

char *func2(int num)
{
    char *buf = malloc(num);
    assert(buf);

    return buf;
}

int main(void)
{
    (func1(10))[0] = '!';    /* wrong */
    (func2(10))[0] = '!';    /* okay */
}

기타 등등...

휴가 후 이런 저런 밀린 일을 정리 하느라 바빠서 간단한 주석이 있는 코드
만 남깁니다. 이해 바랍니다.

--
Jun, Woong (woong at gmail.com)
http://www.woong.org

mushim의 이미지

친절한 답변 감사합니다.

추가로 궁금한것은 함수 안쪽에서만 사용이 가능하겠죠?

다음과 같이는 쓸 수 없을것 같네요.

int num;
int int_array[num];

int main()
{
}

*) 컴파일 해보니, 함수안쪽만 사용가능 하군요. 다음과 같이 에러를 주는군요.

Quote:
variable-size type declared outside of any function
cdpark의 이미지

mushim wrote:
char buf[num];

하고

char *buf = malloc(sizoef(char)*num);

그럼 위의 두 식은 실질적으로 같은 건가요?

variable length array는 그 scope를 벗어나면 자동으로 할당을 해제합니다. 비슷한 함수로 BSD 계열에서 지원되는 alloca()가 있죠.

또, malloc은 heap에, VLA와 alloca는 stack에 잡힌다는 구현의 차이도 있고요.

댓글 달기

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