IT 취미생활.  
Front Page
Tag | Location | Media | Guestbook | Admin   
 
'C'에 해당하는 글(5)
2009.09.10   Hex String to integer 1
2009.07.21   warning: dereferencing type-punned pointer will break strict-aliasing rules
2009.07.01   [warning]suggest parentheses around assignment used as truth value
2009.07.01   Hello World가 실행 파일이 될때까지...
2008.10.17   [알고리즘] Selection Sort


Hex String to integer

이전에 포스팅한 GetProfileToString을 통해서, 특정 값을 읽어왔는데 제기럴 Hex 값이었다.
Int 값이었으면 atoi를 이용해서 int로 쓰겠는데 왠걸 hex string... 열심히 구글링 해보니 CodeProject에 Sample이 있어 업어왔다.


linux에서 왜 string.h에 strupr이 없는걸까???????
보안에 문제가 있는 API라서? 쩝....

Set로 움직이는 함수입니다.
꼭 필요한 분들이 있을 것 같습니다.

수정사항이 있으시면 언제든지!!!  피드백 부탁 드립니다.

고운하루 되세요


char* StrUpr( char *str )
{
    int loop = 0;
    while( str[loop] != '\0' )
    {
        str[loop] = (char) toupper( str[loop] );
        loop++;
    }
    return str;
}


/*
 * hex string to int
*/

int xtoi(char *value)
{
    struct CHexMap
    {
        char chr;
        int value;
    };

    const int HexMapL = 16;
    CHexMap HexMap[HexMapL] =
    {
        {'0', 0}, {'1', 1},
        {'2', 2}, {'3', 3},
        {'4', 4}, {'5', 5},
        {'6', 6}, {'7', 7},
        {'8', 8}, {'9', 9},
        {'A', 10}, {'B', 11},
        {'C', 12}, {'D', 13},
        {'E', 14}, {'F', 15}
    };

    /* remove space */
    int len = strlen(value);
    for(int i = 0; i < len; i++) {
        if( *(value+i) == ' ') {
            value++;
        } else {
            break;
        }
    }

    /* alloc buffer and change upper */
    char *mstr = StrUpr(strdup(value));
    char *s = mstr;
    int result = 0;
    if (*s == '0' && *(s + 1) == 'X')
        s += 2;
    bool firsttime = true;
    while (*s != '\0')
    {
        bool found = false;
        for (int i = 0; i < HexMapL; i++)
        {
            if (*s == HexMap[i].chr)
            {
                if (!firsttime) result <<= 4;
                result |= HexMap[i].value;
                found = true;
                break;
            }
        }
        if (!found) break;
        s++;
        firsttime = false;
    }
    free(mstr);
    return result;
}



warning: dereferencing type-punned pointer will break strict-aliasing rules

Wall로 Build 를 하는데 아래와 같은 워닝이 발생해서

warning: dereferencing type-punned pointer will break strict-aliasing rules

구글링좀 하고, 고치기 귀찮아서  MakeFile만 수정해서 올림
연구원 씨가 관심 있으면 고치겠지.....



The following short examples demonstrate my problem:

----Exhibit A
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int foo;
    int bar;
} item_t;

int return_item (void **item);

int return_item (void **item)
{
    void *mem;

    mem = malloc (1);
    if (mem) {
        *item = mem;
        return 0;
    }
    else
        return 1;
}

int main (int argc, char *argv[])
{
    item_t *item;

    if (return_item ((void **)&item) == 0) {
        printf ("%p\n", item);
        free (item);
    }

    return 0;
}

----Exhibit B
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int foo;
    int bar;
} item_t;

int return_item (void **item);

int return_item (void **item)
{
    void *mem;

    mem = malloc (1);
    if (mem) {
        *item = mem;
        return 0;
    }
    else
        return 1;
}

int main (int argc, char *argv[])
{
    item_t *item;
    void *item_temp;

    if (return_item (&item_temp) == 0) {
        item = item_temp;
        printf ("%p\n", item);
        free (item);
    }

    return 0;
}
----

The code is a generic example of the problem.  The real code that is
producing the problem is a hashing API which hashes (void *) and hence
uses (void **) as an out parameter type. 

Exhibit A produces a warning as follows:

[nodbug:mato]$ gcc -O2 -Wall -o aliasing-test aliasing-test.c
aliasing-test.c: In function `main':
aliasing-test.c:28: warning: dereferencing type-punned pointer will break strict-aliasing rules

I'm using gcc version 3.3.5 (Debian 1:3.3.5-13) but the problem persists
even when tested with GCC 4.x on newer systems.

Exhibit B is my proposed "fix".  Can anyone advise if the code in
Exhibit A is legitimate, i.e. whether or not it's really violating the
strict aliasing rules as defined by the C standard?  If not, then I
guess the warning is spurious and I can safely use the fix.

If the code is in fact violating the standard then feel free to
enlighten me how to fix it, since it seems like a legitimate thing to do
:-)

Thanks very much for any help,
귀차나서 그대로 긁어 왔습니다.

참고 : http://gcc.gnu.org/ml/gcc-help/2006-08/msg00236.html


음 문제가 되면 삭제 하겠습니다 훗..



[warning]suggest parentheses around assignment used as truth value

워닝 발생

if ( x = getSomethingValue())
{
 ........
}

해결방법
if ( (x = getSomethingValue()) )
{
 ........
}

KIN.....



Hello World가 실행 파일이 될때까지...
우선 간단하게 컴파일이 되는 아래 Hello World를 작성한다.

helloworld.c



컴파일러들을 이용하여 실행할 수 있는
실행 파일로 만드는 과정을 간단하게 적어 보면

Preprocessor --> Compiler -->Assembler  --> Linker & Relocation--> executableFile

1. 컴파일러는 helloworld.c 파일을 읽어들인다.
    (확장자에 따라 c / c++로 인식)

2. helloworld.c에 Code를 오브젝트 파일로 만든다.

3. 중간 목적 파일(기계어)로 변경한다 .

4. 중간 목적 파일을 링커 프로그램으로 연결한다.

5. exe  실행파일


[알고리즘] Selection Sort

프로그래밍 불여일타!!의 프로젝트의 일환으로, 퇴근후 배깔고 하는 알고리즘 공부를 시작!!
그 결과물로 간단 간단한 알고리즘을 작성하고, Blog에 올리기로 했습니다.

오늘은 간단하게 Selection Sort를 만들어 보았습니다.

* 원리는 : 총 1...n개의 정렬 되지 않은 요소에서, 첫번째 놈을 가져다가 가장 작은 값을
              가진다라 가정 하고  나머지 n-1개와 비교를 하게 합니다. 그래서 그중 가장
              작은 녀석을 기억 하고 있다가, 1번째 자리와 바꿉니다. 그리고 index을 하나 더
              증가 해서 두번째 요소를 가지고  n-2 만큼 loop를 돌아서 다시 최소값을 찾고
              바꿔 줍니다. 이렇게 반복하면 정렬이 됩니다.( 사실 그림으로 보면 아무것도
              아닙니다. 그림은 귀찮아서 안그렸습니다.)

* 성능 :  O(N^2)

* 코드

void swap( int *a, int *b )
{
     int dump = *a;
     *a = *b;
     *b = dump;
}

void SelectionSort( int *_arrayBuffer, const unsigned int _arraySize )
{
     for( int i = 0; i < _arraySize; i++ )
     {
          int nMinIndex = i;
          for( int j = i + 1; j < _arraySize; j++ )
          {
               if( _arrayBuffer[j] < _arrayBuffer[nMinIndex] )
               {
                   nMinIndex = j;
               }
          }
          swap( _arrayBuffer[nMinIndex], _arrayBuffer[ i ] );
      }  
}


BLOG main image
취미생활
 Notice
 Category
분류 전체보기 (191)
매일매일갱생 (83)
서버개발 (1)
임베디드개발 (12)
Programming (80)
Personal Projects (6)
유용한 프로그램 (0)
 TAGS
C++ Linux 음식 Error Case Java VC++ DirectShow 군대 project Debug english email 1seg 알고리즘 isdbt English Dshow Brazil 출장 티스토리초대 미라지폰 M480 개발자 Wince5.0 영어 이메일 spam mail 서태지 It debugging 벨소리 변경 Algorithm Windows Mobile6.0 티스토리 초대장 warning C 퇴사 DVB-T MP3 DVB ISDB-T
 Calendar
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
 Recent Entries
 Recent Comments
 Recent Trackbacks
 Archive
 Link Site
zextor
괴짜 프로그래머의 일상사~@@
Gag & Peace, and more..
Kazakhstan Almaty.......
Min-A
Sadgarret
Steve Yoon's log
가슴 뛰는 삶을 살아라
오스틴 파워
GUI sin
melanie parker_Lady
제레미의 TV 2.0 이야기..
 Visitor Statistics
Total :
Today :
Yesterday :
rss