Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can union be used to store the value? #16

Closed
openluopworld opened this issue Jun 26, 2016 · 1 comment
Closed

Can union be used to store the value? #16

openluopworld opened this issue Jun 26, 2016 · 1 comment
Labels

Comments

@openluopworld
Copy link

Hello, I have an idea to use an union structure to store the value. Just as follows:

`// union of a cJSON value
typedef union cJSON_Value {
// suppose the size of a pointer is 4-byte. valuestring[1] may be useless.
char *valuestring[2];
int valueint[2];
double valuedouble;
} cJSON_Value;

// struct of cJSON
typedef struct cJSON {
struct cJSON _next,_prev;
struct cJSON *child;
int type;
cJSON_Value value;
char *string;
} cJSON;`

The use of union can reduce the size of a JSON on the sacrifice of the portability. So, it's just a suggestion.

@DaveGamble
Copy link
Owner

It's a fair suggestion, and one that's been around a few times before.
The decision not to do this is based on a desire to /try/ and create some form of type-safety, however marginal. It would be trivial to directly set a double value and hence kill the char*, which is then memory leaked, and causes a crash in free(), etc... and those kinds of mistakes are really easy to make, and will take a long time to hunt down if you're new to the library.

So, yes, it sure could be done, but the memory cost is worth the debug-time cost.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants