sprintf시 버퍼 크기 계산

corba의 이미지

sprintf를 쓸려면 버퍼를 잡아야 합니다.

헌데 이것이 버퍼사이즈가 얼마가 될지 애매한 상황이 자주 발생하더군요.

무작정 많이 잡을수도 없구요...

버퍼오버플로우의 위험도 있구요.

그래서 미리 sprintf로 출력 될 버퍼의 길이를 계산하는 방법은 없는지 궁금합니다.

제가 워낙 C언어에 문외한이라서요 -_ㅡ;

eungkyu의 이미지

corba wrote:
sprintf를 쓸려면 버퍼를 잡아야 합니다.

헌데 이것이 버퍼사이즈가 얼마가 될지 애매한 상황이 자주 발생하더군요.

무작정 많이 잡을수도 없구요...

버퍼오버플로우의 위험도 있구요.

그래서 미리 sprintf로 출력 될 버퍼의 길이를 계산하는 방법은 없는지 궁금합니다.

제가 워낙 C언어에 문외한이라서요 -_ㅡ;

snprintf를 사용하세요.

frowt의 이미지

#include <stdio.h>
int main()
{
    char *p;
    asprintf(&p, "%d", 123);
    printf("%s\n", p);
    return 0;
}
dondek의 이미지

asprintf가 뭐죠?

진리를 나의 수준으로 끌어내리지 마라.
나를 진리의 수준으로 끌어올려라. - 배꼽 중에서

jyj9782의 이미지

snprintf 아닌가요
as 가 아니라 =.=

힘내세요.

jyj9782의 이미지

스트링 n(갯수) print(출력) f(함수)

힘내세요.

dondek의 이미지

아, man에는 안나와서 몰랐는데 asprintf라는게 있군요.
glibc코드를 안봐서 모르겠는데 내부적인 버퍼를 이용하는건가요?

#include <stdio.h>
int main()
{
    char *p;
    asprintf(&p, "%d", 123);
    printf("%s\n", p);
    return 0;
}

위 대로 하면 문제없이 출력을 하는것을 보면 내부 버퍼를 이용하는 모양인데요.

진리를 나의 수준으로 끌어내리지 마라.
나를 진리의 수준으로 끌어올려라. - 배꼽 중에서

정태영의 이미지

dondek wrote:
아, man에는 안나와서 몰랐는데 asprintf라는게 있군요.
glibc코드를 안봐서 모르겠는데 내부적인 버퍼를 이용하는건가요?

제 컴퓨터에는 man 페이지가 있군요 ;)

ASPRINTF(3)                Linux Programmer's Manual               ASPRINTF(3)
                                                                                
                                                                                
                                                                                
NAME
       asprintf, vasprintf - print to allocated string
                                                                                
SYNOPSIS
       #define _GNU_SOURCE
       #include <stdio.h>
                                                                                
       int asprintf(char **strp, const char *fmt, ...);
                                                                                
       int vasprintf(char **strp, const char *fmt, va_list ap);
                                                                                
DESCRIPTION
       The  functions  asprintf  and  vasprintf  are  analogues of sprintf and
       vsprintf, except that they allocate a string large enough to  hold  the
       output  including  the  terminating NUL, and return a pointer to it via
       the first parameter.  This pointer  should  be  passed  to  free(3)  to
       release the allocated storage when it is no longer needed.
 
RETURN VALUE
       When  successful,  these  functions return the number of bytes printed,
       just like sprintf(3).  If memory allocation wasn't  possible,  or  some
       other error occurs, these functions will return -1, and the contents of
       strp is undefined.
                                                                                
NOTES
       These functions are GNU extensions, not in C or POSIX.  They  are  also
       available  under *BSD.  The FreeBSD implementation sets strp to NULL on
       error.
                                                                                
SEE ALSO
       free(3), malloc(3), printf(3)
                                                                                
                                                                                
                                                                                
                                                                                
GNU                               2001-12-18                       ASPRINTF(3)

오랫동안 꿈을 그리는 사람은 그 꿈을 닮아간다...

http://mytears.org ~(~_~)~
나 한줄기 바람처럼..

dondek의 이미지

음. 죄송합니다. 혼자서 장구치고 북치고... -_-;
헤더파일을 보니 이렇게 써 있네요.

/* Write formatted output to a string dynamically allocated with `malloc'.
   Store the address of the string in *PTR.  */

malloc()을 사용하도록 되어있군요.
사용한 후에 free()해줘야 하네요.

진리를 나의 수준으로 끌어내리지 마라.
나를 진리의 수준으로 끌어올려라. - 배꼽 중에서

frowt의 이미지

asprintf 를 얘기했던사람입니다.
free 를 빼먹었군요..
예전에 온라인문서에서(glibc관련) 보고 알게 되었습니다.
업무상으로나 실서비스에서 사용을 해보지는 않았습니다.
asprintf 내부에서 malloc 하는것으로 알고있습니다.

corba의 이미지

많은 분들의 답변 감사합니다. ^^;

그런데 불행히도 asprintf가 vc엔 없더군요 ^^;

그래서 vasprintf의 소스를 구해서 거기서 계산하는 모듈을 발췌해서 사용했습니다.

다들 행복하세요...

pynoos의 이미지

a- 계열의 printf는 없는 OS가 많습니다.
있으면 좋은 것임에도 불구하고 그렇지요.

http://www.ijs.si/software/snprintf/

여기에 가시면 공개용 snprintf 가 있습니다. 필요하시면 참고하셔요..

댓글 달기

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