0
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.

2015-07-25 c++ builder > JSON > ファイル読込み > ParseJSONValue() / Size() / JsonString->Value() / JsonValue->Value() > メモリリークコード修正

0
Last updated at Posted at 2015-07-24

http://qiita.com/7of9/items/41d8b9adb06a6e930058
にて書き出したファイルからの読み込み

code v0.1 > メモリリークあり

# include <DBXJSON.hpp> // for JSON
# include <memory> // for unique_ptr

...

	std::unique_ptr<TStringList> slread(new TStringList);
	slread->LoadFromFile(L"test.json");

	TJSONObject *jsonObj = new TJSONObject();
	String jsonKey, jsonValue;
	TJSONPair *pairObj;

	for(int li=0; li < slread->Count; li++) { // file line index
		String jsonText = slread->Strings[li];
		jsonObj = dynamic_cast<TJSONObject*>(TJSONObject::ParseJSONValue(jsonText));

		for(int pi=0; pi < jsonObj->Size(); pi++) { // pair index
			pairObj = jsonObj->Get(pi);
			jsonKey = pairObj->JsonString->Value();
			jsonValue = pairObj->JsonValue->Value();
			ShowMessage(jsonKey + ":" + jsonValue);
		}
	}
	jsonObj->Free();

code v0.2 > メモリリーク修正

(追記 2016/07/28)

上記の実装ではjsonObj に関してメモリリークが生じることをFastMMで確認した。

jsonObj を定義する時にjsonObj = new TJSONObject();をしているが、そのjsonObjを使わずにjsonObj = dynamic_cast<...>としているため、メモリリークが発生している。

以下が正しいコードと思われる。

# include <DBXJSON.hpp> // for JSON
# include <memory> // for unique_ptr

...

	std::unique_ptr<TStringList> slread(new TStringList);
	slread->LoadFromFile(L"test.json");

	TJSONObject *jsonObj;
	String jsonKey, jsonValue;
	TJSONPair *pairObj;

	for(int li=0; li < slread->Count; li++) { // file line index
		String jsonText = slread->Strings[li];
		jsonObj = dynamic_cast<TJSONObject*>(TJSONObject::ParseJSONValue(jsonText));

		for(int pi=0; pi < jsonObj->Size(); pi++) { // pair index
			pairObj = jsonObj->Get(pi);
			jsonKey = pairObj->JsonString->Value();
			jsonValue = pairObj->JsonValue->Value();
			ShowMessage(jsonKey + ":" + jsonValue);
		}
	}
	jsonObj->Free();

備考

(追記 2019-05-07)

フォルダをJSONのvalueとしている場合は、下記のような対応をする必要がある場合がある。

		// フォルダに使われる"\"の扱いによるエラー対応のため
		jsonText = StringReplace(jsonText, L"\\", L"\\\\", TReplaceFlags()<<rfReplaceAll);
0
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
0
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?