strncpy 어떻게들 처리하십니까 ?

kicom95의 이미지

소시적에 프로그래밍할때 -_-;; 지금도 소시적 입니다만.

strncpy 가 NULL 문자를 끝에 기록을 안해주는 버젼이 있어...

아마 windows 지요...

memset 을 한후 strncpy 를 쓰는데......

다른 방법이 있나 해서요 ^^

지금 상황에서... memset 부하도 줄여야 하므로 ㅋㅋㅋ

정태영의 이미지

kicom95 wrote:
소시적에 프로그래밍할때 -_-;; 지금도 소시적 입니다만.

strncpy 가 NULL 문자를 끝에 기록을 안해주는 버젼이 있어...
아마 windows 지요...

memset 을 한후 strncpy 를 쓰는데......
다른 방법이 있나 해서요 ^^

지금 상황에서... memset 부하도 줄여야 하므로 ㅋㅋㅋ

윈도우 만이 아니라 원래가 그런거 같은데요 :)

man strncpy wrote:
The strncpy() function is similar, except that not more than n bytes of
src are copied. Thus, if there is no null byte among the first n bytes
of src, the result will not be null-terminated.

이렇게 명시되어 있으니까요...

strncpy( dst, src, n );
dst[n] = '\0';

정도면 되지 않을까 싶은데요 :)
길이가 n보다 짧다면 null 까지 복사될테고... 아니라면 null terminated 라는 보장이 없으니까 후자일 경우에 한해서 문제를 일으키지 않도록 해주면 되겠죠

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

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

정태영의 이미지

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

#include <string.h>

int main( int argc, char** argv ){

        char* src = "1234567890";
        char  dst[20];

        dst[19] = 0;
        memset( dst, 'a', 19 );
        strncpy( dst, src, 5 );

        fprintf( stderr, "copy up to 5 bytes :D\n" );
        fprintf( stderr, "src: %s, len(%d)\n", src, strlen(src) );
        fprintf( stderr, "dst: %s, len(%d)\n", dst, strlen(dst) );

        fprintf( stderr, "\n" );

        memset( dst, 'a', 19 );
        strncpy( dst, src, 11 );

        fprintf( stderr, "copy up to 15 bytes :D\n" );
        fprintf( stderr, "src: %s, len(%d)\n", src, strlen(src) );
        fprintf( stderr, "dst: %s, len(%d)\n", dst, strlen(dst) );

        return 0;

}

위의 코드를 이용해서 테스트를 했고...
전 젠투 리눅스 에서 gcc 3.3.5 버젼을 이용해서 테스트를 했습니다 glibc 2.3.5 버젼이 깔려있구요...

결과는 아래와 같이 예상한 결과가 그대로 나오는군요 :)

Quote:

copy up to 5 bytes :D
src: 1234567890, len(10)
dst: 12345aaaaaaaaaaaaaa, len(19)

copy up to 15 bytes :D
src: 1234567890, len(10)
dst: 1234567890, len(10)

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

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

kicom95의 이미지

strncpy 를 처음 사용할때... -_-;;

NULL 문자가 붙지 않은 경험을 한후...

무조건 memset 을 했다는 OTL -_-;;

감사합니다 ^^

가자 해외로 ~ .. 돈 벌러.

j0nguk의 이미지

strlcpy는 어떻습니까?

cinsk의 이미지

strncpy()는 일반적으로 쓰면 안되는 함수입니다. :wink:

char *strncpy(char *dst, const char *src, size_t n);

뭐.. 특별히 위험한 점은 없으나, 세번째 인자보다 작은 문자열이 들어왔을 때, 그 차이만큼 '\0'로 계속 쓰게 되므로, 효율성에서 좋은 함수가 아닙니다. 게다가 n보다 크거나 같은 길이의 SRC가 들어올 경우, '\0'로 끝내주지 않으므로 일일히 검사하기도 번거롭습니다. 따라서 다음과 같이 만들어 두고 쓰는 것이 좋습니다:

char *
xstrncpy(char *dst, const char *src, size_t n)
{
  dst[0] = '\0';
  return strncat(dst, src, n - 1);
}
정태영의 이미지

strlcpy 는... bsd에만 있는 건가요? c99 문서에 string.h 부분에서는 해당 함수가 없군요... man strlcpy 를 해봐도 없구요 :) glibc 에는 그런 함수가 없는 듯 한데요

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

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

moonzoo의 이미지

snprintf 도 쓸만하더군요.

sangwoo의 이미지

정태영 wrote:
strlcpy 는... bsd에만 있는 건가요? c99 문서에 string.h 부분에서는 해당 함수가 없군요... man strlcpy 를 해봐도 없구요 :) glibc 에는 그런 함수가 없는 듯 한데요

표준은 아니고.. 아마 OpenBSD에서 젤 처음 만들어진 녀석일 겁니다.
상당히 편하고 안전합니다. :-)

----
Let's shut up and code.

j0nguk의 이미지

정태영 wrote:
strlcpy 는... bsd에만 있는 건가요? c99 문서에 string.h 부분에서는 해당 함수가 없군요... man strlcpy 를 해봐도 없구요 :) glibc 에는 그런 함수가 없는 듯 한데요

그렇군요. OpenBSD에서 처음 만들어졌고, 표준이 아니라고 알고 있었는데, 아까 글 쓰기전 확인차 man strlcpy를 했더니,

LIBRARY
Standard C Library (libc, -lc)

라고 되어있길래 "표준으로 채택되었나? @.@" 했습니다. 역시 아니군요.
:shock:

HISTORY
The strlcpy() and strlcat() functions first appeared in OpenBSD 2.4, and
made their appearance in FreeBSD 3.3.

꽤 오래전에 만들어진 녀석이고 개인적으로 프로그램 짤 때 많이 썼었는데, 표준이 아니었군요. 정보 감사합니다. :)

댓글 달기

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