[英]converting an address of a struct to string
我正在嘗試將結構地址轉換為字符串,但我嘗試了兩種編寫代碼的方法。 第一個導致了 valgrind 的錯誤,而第二個沒有。 這是我在重用 valgrind 時唯一改變的想法,但結果不同。 如果您能說出問題所在,我將不勝感激。
第一個:
typedef struct Unit_t *Unit;
//Creating a unit
char* unit_address = malloc(sizeof(unit) + 1);
int convert_result = sprintf(unit_address,"%p",(void*)unit);
//Checking the return result and freeing the allocated memory
第二個:
typedef struct Unit_t *Unit;
//Creating a unit
char unit_address[30];
int convert_result = sprintf(unit_address,"%p",(void*)unit);
//Checking the return result
我想分配 memory 因為我不能假設指針的長度是多少(至少不是在我正在做的硬件中)。
sizeof(unit)
是unit
的二進制表示的字節數。
在某些環境中,它會小於字符串表示中使用的字節數。
例如,如果指針長度為 4 字節,並且它們以 8 位十六進制字符串表示,則sizeof(unit)
(=4) 小於表示字符串的長度 (=8) 並且會發生越界寫入.
動態分配 memory,
示例實現(應添加錯誤檢查並應使用snprintf()
而不是sprintf()
以使其更安全):
char unit_address_buffer[512];
int convert_result = sprintf(unit_address_buffer,"%p",(void*)unit);
char* unit_address = malloc(strlen(unit_address_buffer) + 1);
strcpy(unit_address, unit_address_buffer);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.