jsoncpp icon indicating copy to clipboard operation
jsoncpp copied to clipboard

Exceptions while parsing in Debug configuration, but not Release configuration

Open mboedigh opened this issue 6 years ago • 7 comments

Describe the bug Parsing works correctly when I compile in release configuration, but throws an exception in debug configuration. I get the suspicious feeling this has been asked and answered, but I don't see it anywhere. I tried using the example from https://open-source-parsers.github.io/jsoncpp-docs/doxygen/index.html#_example as a guide, but that throws in the same manner.

To Reproduce

  1. Compile the following code in debug configuration in visual studio 16.8.2 and run (from within VS)
#include <sstream>
#include <iostream>
#include <vector>
#include <json/json.h>
auto json_str = R"({
    "Units": [
        {
            "id": 0,
            "name": "NotAUnit"
        },
        {
            "id" : 1,
            "name" : "System_Snapshot_Dummy"
        }
    ]
})";

int main() {
    std::stringstream fin(json_str);
    Json::Value root;
    fin >> root;
    Json::Value units = root["Units"];
    for (Json::ArrayIndex i = 0; i < units.size(); ++i) {
        const Json::Value a = units[i];
        auto              b = a["name"];
        std::cout << b << std::endl;                  // ok
        std::cout << b.asString() << std::endl;  // problem here 
    }
    return 0;
}

Desktop (please complete the following information):

  • OS: Windows 10

Expected output:* output when compiled in Release configuration

"NotAUnit"
NotAUnit
"System_Snapshot_Dummy"
System_Snapshot_Dummy

mboedigh avatar Nov 28 '20 18:11 mboedigh

do you have more details on the nature of the exception? a stack trace perhaps?

On Sat, Dec 12, 2020 at 3:15 AM o-super [email protected] wrote:

I am experiencing the same issue. (Windows 10)

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/open-source-parsers/jsoncpp/issues/1243#issuecomment-743722244, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABYXGPDJ27DEAL2DET5U7VDSUMRBNANCNFSM4UF67NJA .

-- ǝnɥɐuop ʎllıq

BillyGoto avatar Dec 13 '20 05:12 BillyGoto

Thanks for the reply. When I run in debug mode the output is

"NotAUnit"
NotAUnit

And then I get an exception with the following stacktrace:

>	unit_range.exe!free_dbg_nolock(void * const block, const int block_use) Line 996	C++
 	unit_range.exe!_free_dbg(void * block, int block_use) Line 1030	C++
 	[External Code]	
 	unit_range.exe!std::_Deallocate<16,0>(void * _Ptr, unsigned __int64 _Bytes) Line 221	C++
 	unit_range.exe!std::_Default_allocator_traits<std::allocator<std::_Container_proxy>>::deallocate(std::allocator<std::_Container_proxy> & __formal, std::_Container_proxy * const _Ptr, const unsigned __int64 _Count) Line 690	C++
 	unit_range.exe!std::_Deallocate_plain<std::allocator<std::_Container_proxy>>(std::allocator<std::_Container_proxy> & _Al, std::_Container_proxy * const _Ptr) Line 999	C++
 	unit_range.exe!std::_Delete_plain_internal<std::allocator<std::_Container_proxy>>(std::allocator<std::_Container_proxy> & _Al, std::_Container_proxy * const _Ptr) Line 1028	C++
 	unit_range.exe!std::string::~basic_string<char,std::char_traits<char>,std::allocator<char>>() Line 2808	C++
 	unit_range.exe!main() Line 27	C++
 	[External Code]	

mboedigh avatar Dec 13 '20 18:12 mboedigh

Hello mboedigh,

Simply remove the const will fix your issue.

const Json::Value a = units[i];

Note that it is always a bad idea to declare variables inside a loop.

I have reworked your code, here is an example using a builder to parse your JSON and protecting the call by checking if the member exists before accessing to it. I hope it will help.

#include <iostream>
#include <vector>
#include <json/json.h>
auto json_str = R"({
    "Units": [
        {
            "id": 0,
            "name": "NotAUnit"
        },
        {
            "id" : 1,
            "name" : "System_Snapshot_Dummy"
        }
    ]
})";

int main()
{
	std::string   jsonStr = json_str;
	Json::Value   root;	
	Json::Value   units;
	Json::Value   a;
	std::string   b;
	
	// This values should be stored in class and not created every time we want to parse
	Json::CharReaderBuilder			builder;
	std::unique_ptr<Json::CharReader>	reader(builder.newCharReader());
	JSONCPP_STRING				error;

	try
	{
		if (!reader->parse(jsonStr.c_str(), jsonStr.c_str() + jsonStr.length(), &root, &error))
		{
			std::cout << ("Parsing Error") std::endl;
			return (-1);
		}
		// Check if packet root contains elem "Units"
		if (!root.isMember("Units"))
		{
			// Json not shaped like expected no need to continue
			return (-1);
		}
		// Assigned units and look for members / values
		units = root["Units"];
		for (Json::ArrayIndex i = 0; i < units.size(); ++i)
		{
			if (units[i].isMember("name"))
			{
				b = units[i]["name"].asString();
				std::cout << b << std::endl;
			}
			else
			{
				std::cout << "Name is not a member, here is the list of members available:" << std::endl;
				std::vector<std::string> names = units[i].getMemberNames();
				for (int namesCount = 0; namesCount < names.size(); namesCount++)
				{
					std::cout << names[namesCount] << std::endl;
				}
			}
		}
	}
	catch (const std::exception& e)
	{
		std::cout << "Exception error!" << std::endl;
		return (-1);
	}
	return (0);
}

o-super avatar Dec 13 '20 20:12 o-super

Hello mboedigh,

Simply remove the const will fix your issue.

const Json::Value a = units[i];

Note that it is always a bad idea to declare variables inside a loop.

Why? I don't see the risk.

Thanks for identifying a more minimal clue. It looks like there's a bug inside Json::Value's accessors if the const qualification on a makes the difference. Maybe we're casting away const-ness of a declared-const object inappropriately somewhere.

BillyDonahue avatar Dec 14 '20 16:12 BillyDonahue

I still have the problem after removing const.

    for (Json::ArrayIndex i = 0; i < units.size(); ++i) {
        Json::Value a = units[i];
        auto        b = a["name"];
        std::cout << b << std::endl;                 // ok
        std::cout << b.asString() << std::endl;      // problem still remains
    }

mboedigh avatar Dec 14 '20 18:12 mboedigh

mboedigh,

Can you make sure you are running your project with the debug dll? I made another test, it appears the issue exist only when I am compiling in debug mode (link to the debug library) but executing the project with the release dll.

No need to remove the const in the end, I must have changed my configuration while I was testing the other day and didn't catch it was what solved the issue.

o-super avatar Dec 14 '20 19:12 o-super

ARGGH. I'm using vcpkg to integrate into my Visual Studio project. As far as I can tell, Jsoncpp is not included or linked. I don't see it in the command line and I don't see it in the build log. I fully don't understand how it compiles at all. Good thing I have this build system to make my (and your) life easy, huh? I do know that it must be on me though, because in a brand new project the above sample compiles and runs fine. I was trying to be helpful, but instead am sorry to waste your time. You can close this item.

mboedigh avatar Dec 15 '20 17:12 mboedigh