簡體   English   中英

在struct元素上使用memset的正確方法是什么?

[英]What is the proper way to use memset on a struct element?

我試圖在結構元素上使用memset,如下所示:

memset( &targs[i]->cs, 0, sizeof( xcpu ) );

但是,這樣做會給我一個分段錯誤。 我既不明白為什么會失敗,也不知道我怎么能讓它發揮作用。 在結構元素上使用memset的正確方法是什么,為什么我的方法不起作用?

為targs分配內存的行:

eargs **targs = (eargs **) malloc(p * sizeof(eargs *));

struct element cs(xcpu_context)和struct targs(execute_args)的結構定義:

typedef struct xcpu_context {
  unsigned char *memory;              
  unsigned short regs[X_MAX_REGS];    
  unsigned short pc;                  
  unsigned short state;              
  unsigned short itr;                 
  unsigned short id;                 
  unsigned short num;                 
} xcpu;

typedef struct execute_args {
    int ticks;
    int quantum;
    xcpu cs;
} eargs;

您已在行中分配了一組指針

eargs **targs = (eargs **) malloc(p * sizeof(eargs *));

但是你沒有初始化元素本身。 因此,這個段錯誤與在結構的字段上正確使用memset無關,而是使用uininitialized內存(假設在分配指針數組后沒有用於初始化每個eargs對象的循環)。

相反,如果你想分配一個p eargs對象的動態數組(我在這里松散地使用術語“對象”),你會寫

eargs *args = malloc(p * sizeof(eargs));
if (!args) {
    /* Exit with an error message */
}
memset(&(args[i].cs), 0, sizeof(xcpu));

代替。 請注意, args是一個動態分配的eargs對象數組, 而不是動態分配的指針數組,所以它的類型為eargs *而不是eargs **

您的內存分配行不為任何結構分配任何內存,僅用於指向結構的指針。 如果要為整個數組分配內存,則需要添加一個循環來為結構本身分配內存:

for (i = 0; i < p; i++)
    targs[i] = malloc(sizeof(eargs));

一旦你真的結構來操作,你的memset()調用應該沒問題。

暫無
暫無

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

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