0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ポインタにmemcpyする

Last updated at Posted at 2020-12-09

備忘録
※2021/2/3 追記

ダメなほう


char *hoge;
char str[5] = "test";

memcpy(hoge, &str[0], sizeof(str));

// hogeからtestを読み出したいが
// 読み出すと変な値

正しいほう

char Secure_str[5] = {"\0"};
// この初期化で書き込める領域を確保
char *hoge = &Secure_str;
char str[5] = "test";

memcpy(hoge, &str[0], sizeof(str));

// hogeからはtestが読み出せる

アドレス入れられる領域を確保をしないとだめ

追記

(コメントでご指摘いただいた内容をそのまま記載しています)

アドレス入れられる領域を確保をしないとだめ

データを入れる領域を確保しないとだめです。

char *hoge;

ポインタ変数を宣言することでアドレスを入れる領域を確保しています。
アドレスを代入していないので、どこをアドレス(ポイント)しているか不明な状態です。

char Secure_str[5] = {"\0"};

これでデータ領域を確保しています。

char *hoge = &Secure_str;

これで、データ領域のアドレスをポインタ変数に代入しています。
ポインタ変数hogeはデータ領域Secure_strをポイントしています。

memcpy(hoge, &str[0], sizeof(str));

これは、「hoge変数に代入されている値(どこかのアドレス)」と「str[0] のアドレス」と 「str領域のサイズ」を引数にして「memcpy関数」を呼び出しています。
最初のコードは、hoge変数に値が代入されていないため不定値を渡してしまい、memcpy関数はおかしな動作をします。

0
0
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?