간단한 프로그램 문제 질문

asleea의 이미지

밑의 두 함수는 사용자 입력으로 char buf에 String 값으로 16진수 값을 주면그 값을 실제 16진수 값으로 변경하여 byte단위로 저장하도록하고, 그 바이트 단위로 저장된 hex값을 출력하는 각각의 함수입니다.

그런데 HexStringToBytes함수중 (1)번을 보면 2로 나누어 떨어지지 않으면 잘못된 값으로 인식을 하는데 사용자 입력으로 만약 1234를 입력하면 개항문자가 합처져

strlen는 5나오는 것으로 알고 있어 이상하게 생각하여 test를 해보았습니다.

그런데 이상한 현상이 발생합니다. 입력으로 1234 입력시 main문의 출력결과 rtn값은 예상대로 5가 나왔지만 strlen값이 12가 나왔습니다.(main함수의 (2)부분)

그리고 main문에 hexStringToByte, print_in_hexa함수 호출을 주석처리 하고 실행을 하면 예상대로 rtn = 5, strlen = 5가 나옵니다.

왜 이러는지 .ㅜㅜㅜㅜ

/////////////////////////////////////////main문의 두 함수 호출을 주석 처리시 출력 결과

1234 <- 사용자 입력
rtn : 5
strlen : 5
a : 1234
/////////////////////////////////////////main문의 두 함수 호출하여 출력 결과

1234 <- 사용자 입력
rtn : 5
strlen : 12
a : 1234
�X�pRr�len:2 data:12 34

////////////////////////////////////////

즉 위의 두 함수를 호출하면 뒤에 NULL을 붙여주지 않는 듯하고, 호출하지 않으면 NULL을 붙여주는 듯합니다.

제 개념으로는 아무리 생각을 해도 원인을 모르겠습니다.

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/time.h>
#include<string.h>
unsigned char nibbleFromChar(char c)
{
    if(c >= '0' && c <= '9') return c - '0';
    if(c >= 'a' && c <= 'f') return c - 'a' + 10;
    if(c >= 'A' && c <= 'F') return c - 'A' + 10;
    return 255;
}
int hexStringToBytes(char *hexString, char *bytes)
{
    int len, i;
    if(strlen(hexString)%2 != 0){.................................................................(1)
        //잘못된 hexString인 경우
        return -1;
    }
    len=strlen(hexString)/2;
 
 
 
    for(i=0;i<len;i++)
    {
        bytes[i] = (nibbleFromChar(*hexString) << 4) + nibbleFromChar(*(hexString+1));
        hexString+=2;
    }
 
    return len;
}
 
void print_in_hexa(unsigned char *buf, int len)
{
    int i;
    printf("len:%d\t data:", len);
    for(i=0;i<len;i++) {
        printf("%02X ", buf[i]);
    }
    printf("\n");
}
int main()
{
    char a[10];
    char bytes[10];
    int rtn;
    rtn = read(STDIN_FILENO, a, 10);
    printf("rtn : %d\n", rtn);
    printf("strlen : %d\n", strlen(a));...............................................(2)
    printf("a : %s", a);
 
    hexStringToBytes(a, bytes);
    print_in_hexa(bytes, 2);
 
    return 0;
}
chadr의 이미지

배열 a를 0으로 초기화 한 후에 해보세요.

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

댓글 달기

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