alignment와 padding 질문

송지석의 이미지

다음 같은 구조체가 있습니다.

typedef struct {
    char a;
    char b;
    short c;
    int aa[3];
    char str[MAX];
} t_myType;

저는 PPC860에서 프로그래밍 중인데 통신에서 사용하려고 pack시켰습니다.
컴파일러 옵션에 -fpack-struct 를 사용했지요. 필요한 것만 __attribute__((packed)) 를 사용하면 됩니다만 예전부터 다른 사람들이 했던 소스라 고치기가 뭐해서 그냥 쓰고 있습니다.

그런데 map 파일을 보니 메모리상에 적재될 때 홀수 주소로 올라가더군요.
pack은 하지만 잘 보면 4byte로 맞춰져있습니다. 그래서 위 타입 같은 경우 4byte align 맞는 곳에 올라갔으면 하는데요. 그걸 보고 자세히 다른 변수들도 보니까 모든 변수들이 다 4byte align을 안맞추고 올라갑니다. short난 int(32bit) 변수들도 홀수번지에 적재되는 거죠.
문제는 저런식으로 만이아니고 그냥 별 생각 없이 사용하던 패킷 타입도 있을 것이란 것입니다. 그래서 컴파일러 pack 옵션은 놔두고 align만 4byte로 시작하게 할 방법이 없을까요? 변수들의 시작주소만 4byte를 맞추게 말이죠.

cdpark의 이미지

위 선언 순서라면 굳이 pack 옵션 없이도 잘 packing될 듯 싶은데요? (MAX 값이 4의 배수라면요.) 확인해보세요.

송지석의 이미지

위에 썼듯이 제가 만든 구조체들은 4byte 씩 되는데요, 다른 사람이 쓴 것을 확신하지 못하기 때문에 pack 옵션은 켜두고 변수들이 올라가는 첫 주소의 align만 맞출 수 있을까 해서요.

sunyzero의 이미지

송지석 wrote:
다음 같은 구조체가 있습니다.
typedef struct {
    char a;
    char b;
    short c;
    int aa[3];
    char str[MAX];
} t_myType;


typedef struct {
    char a;
    char b;
    short c;
    int aa[3];
    char str[MAX] __attribute__((aligned(4)));
} t_myType;

로 하신 str[] 은 4byte로 align 됩니다. 물론 gcc. 다른 cc에서는 pragma 로 맞추는데 옵션기억이 안납니다. ㅠ.ㅠ

========================================
* The truth will set you free.

송지석의 이미지

sunyzero wrote:
송지석 wrote:
다음 같은 구조체가 있습니다.
typedef struct {
    char a;
    char b;
    short c;
    int aa[3];
    char str[MAX];
} t_myType;


typedef struct {
    char a;
    char b;
    short c;
    int aa[3];
    char str[MAX] __attribute__((aligned(4)));
} t_myType;

로 하신 str[] 은 4byte로 align 됩니다. 물론 gcc. 다른 cc에서는 pragma 로 맞추는데 옵션기억이 안납니다. ㅠ.ㅠ

그렇게 하면 str만 4byte align되는 건가요? 저는 t_myType의 처음이 4byte align 맞춰서 올라갔으면 하는데..
혹시
t_myType myvar1 __attribute__((aligned(4)));
t_myType myvar2 __attribute__((aligned(4)));

이렇게 하면 pack은 되면서 &myvar1, &myvar2는 4의 배수가 되나요?
onlytobe의 이미지


▣ Data Alignment 에 따른 문제 해결 방법

1.	컴파일 시 전체를 (n) byte alignment 해주는 방법
     -	gcc 컴파일러인 경우 컴파일 시 –fpack-struct 옵션 사용
     -	공유 라이브러리는 1byte alignment를 고려하지 않기 때문에 전체 데이       터를 alignment 하는 것은 굉장히 위험함 

2.	#pragma pack을 이용하여 범위지정
    -	구조체나 클래스를 선언할 때 (n) byte alignment 하기 위해서 선언하  기 전 #pragma pack(n)을 하고 선언 후에 #pragma pack()을 하여 원래 데이터 alignment로 반환하는 방법

   - ex)  2byte alignment 인 경우

    #pragma pack(2)    //2byte alignment 

     /*
        데이터 선언 부분 
      */
    #pragma pack()     // 원래 데이터형 alignment


      



3.	데이터 정의 헤더파일 통째로 alignment하는 경우
    -	pack 기능 중 push와 pop을 이용
    -	ex) 정의 헤더 파일이 “define.h” 이고 2byte alignment인 경우

    #pragma pack(push,2)
    #include “define.h”
    #pragma pack(pop)

 4.	 __attribute__((packed)) 을 이용하여 struct나 class 선언시 개별적  으로 지정 (gcc 컴파일러인 경우 )

   -	ex) struct  __attribute__((packed)) A_Data{
                          char c;
                          int i;
             } ;



댓글 달기

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