簡體   English   中英

如何用特定值填充非緊湊結構的所有填充字節?

[英]How can I fill all padding bytes of a non-compact struct with a specific value?

我們知道,出於對齊原因,結構可以具有內部填充字節。

如何用特定值填充非緊湊結構的所有填充字節? 換句話說,請考慮以下代碼段:

struct Foo;

// Is that possible to implement pad_Foo() function? If Yes, How?
void pad_Foo(struct Foo *pFoo_x, char pad_byte);

void bar(struct Foo *pFoo_x, int fd, char pad_byte)
{
    // reading in *pFoo_x from a file.
    // It may get some garbage padding bytes.
    read(fd, pFoo_x, sizeof(struct Foo));

    pad_Foo(&x, pad_byte);
}

是否可以實現pad_Foo()函數,如果答案是肯定的,怎么辦?

是否可以實現pad_Foo()函數

作為符合標准的代碼,答案是否定的

根據C11草案n1570中的6.2.6類型表示:

6當值存儲在結構或聯合類型的對象中(包括成員對象中)時,與任何填充字節相對應的對象表示形式的字節采用未指定的值 51)

51)因此,例如,結構分配不需要復制任何填充位。

因此標准明確指出:填充的值無法控制。

在特定的系統(平台,操作系統,編譯器)上,這是可能的。 以我的系統為例:

# include <stdio.h>
# include <string.h>

struct s
{
  char c;
  int n;
};

void dump_struct(struct s * p)
{
  unsigned char * u = (unsigned char *)p;
  for (size_t i=0; i < sizeof *p; ++i) printf("%02x ", u[i]);
  printf("\n");
}

int main(){
  printf("sizeof(struct s)=%zu sizeof(char)=%zu sizeof(int)=%zu padding=%zu\n",
         sizeof(struct s), 
         sizeof(char), 
         sizeof(int), 
         sizeof(struct s) - sizeof(char) - sizeof(int));

  struct s sa;
  memset(&sa, 'A', sizeof sa);
  sa.c = '8';
  sa.n = 42;
  dump_struct(&sa);

  struct s sb;
  memset(&sb, 'B', sizeof sa);
  sb.c = '8';
  sb.n = 42;
  dump_struct(&sb);
}

輸出:

sizeof(struct s)=8 sizeof(char)=1 sizeof(int)=4 padding=3
38 41 41 41 2a 00 00 00
38 42 42 42 2a 00 00 00
   ^^^^^^^^
    notice

因此,在我的系統上, memset確實寫入了填充字節,但是在其他系統上,您可能會看到不同的行為。

main添加這樣的代碼:

  unsigned char * u = (unsigned char *)&sb.c;
  u += sizeof sb.c;
  while(u < (unsigned char *)&sb.n)
  {
    *u = 'C';
    ++u;
  }
  dump_struct(&sb);

將打印多余的行:

38 43 43 43 2a 00 00 00

同樣,在我的特定系統上,填充已更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM