3
1

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 5 years have passed since last update.

C言語の動的メモリ確保時の null チェック

Posted at

メモ

udemy で、C言語のポインタを学習している際に、警告が出てきたので対応方法のメモ

開発環境

Visual Studio 2019 Community
Windows 10

ダメなコード

# include <stdio.h>
# include <stdlib.h>
# define SIZE 3
void main() {
	int* p1 = NULL;
	double* p2 = NULL;
	int i;
	// 動的にメモリ確保
	p1 = (int*)malloc(sizeof(int) * SIZE);
	p2 = (double*)malloc(sizeof(double) * SIZE);

	// 値のセット
	for (i = 0; i < SIZE; i++)
	{
		p1[i] = i;
		p2[i] = i / 10.0;
	}
	// 値の表示
	for (i = 0; i < SIZE; i++)
	{
		printf("p1[%d] = %d, p2[%d] = %lf\n", i, p1[i], i, p2[i]);
	}
	// メモリ領域の解放
	free(p1);
	free(p2);
}

上記のサンプルコードの場合、VS2019 環境ではエラーが発生する

NULL ポインター 'p1' を逆参照しています。
NULL ポインター 'p2' を逆参照しています。

エラーコード:C6011(Microsoftサイトへのリンク)

原因

NULL かもしれない変数に値を入れようとしているから、エラーになる。変数を使う前に、NULLかどうかのチェックを入れれば、OK

エラーが起きないコード

# include <stdio.h>
# include <stdlib.h>
# define SIZE 3

void main() {
	int* pointer_int = NULL;
	double* pointer_double = NULL;
	int i;
	// 動的にメモリ確保
	pointer_int = (int*)malloc(sizeof(int) * SIZE);
	pointer_double = (double*)malloc(sizeof(double) * SIZE);
	// 値のセット
	for (i = 0; i < SIZE; i++)
	{
		if( pointer_int != NULL ) 
			pointer_int[i] = i;
		if( pointer_double != NULL) 
			pointer_double[i] = i / 10.0;
	}
	// 値の表示
	for (i = 0; i < SIZE; i++)
	{
		if (pointer_int != NULL && pointer_double != NULL)
		{
			printf("pointer_int[%d] = %d, pointer_double[%d] = %lf\n", i, pointer_int[i], i, pointer_double[i]);
		}
	}	
	// メモリ領域の解放
	free(pointer_int);
	free(pointer_double);
}

ポインタ変数を使用する前に、変数の中身をチェックする。

3
1
0

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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?