Hi Rifo,
> Thanks a lot for your help. I was busy with other problems and just
> found the time to work on this issue. Following your advice and going
> through other forum posts. I prepared the below code. Can you please
> have a quick look and comment on it, I am not really sure whether I
> was able to free the resources correctly?
Great! Thanks for posting code; it makes it much easier to help out.
Please see comments inline.
> |
> intmain(intargc,char*argv[])
> {
> doublecoordinates[10]={27.6071834564209,38.58359966761715,
> 27.608342170715332,38.584807345233095,
> 27.608299255371094,38.58953722034559,
> 27.604308128356934,38.591650468096404,
> 27.613234519958496,38.5771583773376};
> size_t i;
> char*text;
>
> json_t *root;
> json_error_t error;
>
> json_t *array2 =json_array();
>
>
> for(i =0;i <5;i++){
> json_t *array =json_array();
> json_array_append_new(array,json_real(coordinates[2*i]));
> json_array_append_new(array,json_real(coordinates[2*i+1]));
> json_array_append_new(array2,array);
> |
|You can replace the above four lines with the following:
json_array_append_new(array2,
json_pack("[ff]",
coordinates[2*i],
coordinates[2*i+1]));
Both are equivalent, but I find this version simpler. (It's up to you,
of course!)
|
> |
> // TODO: Ask below question?
> // Is it true that when I later on use json_decref(array2)
> // all the resources allocated for json_t* array in the for loop
> // will be freed too?
>
> }
>
> root =json_pack("{s:s,s:[{s:s,s:{},s:{s:s,s:o}}]}",
> "type","FeatureCollection","features","type","Feature","properties",
> "geometry","type","LineString","coordinates",array2);
>
> text =json_dumps(root,JSON_INDENT(2));
> puts(text);
> free(text);
>
> // free resources
> json_decref(root);
> json_decref(array2);
> |
There's a double-free bug here. When you pack array2 into root, you
steal a reference to array2. That means "decref(root)" also frees
"array2"|, and it's incorrect to free it again.||
If you want to re-use 'array2' after freeing 'root', use "s:O" in the
json_pack string above. That will obtain a second reference for 'root',
and you will need to decref(array2) as above.
For debugging reference counting, I recommend you try valgrind: it makes
it trivial to double-check that all your references are freed.
best,
Graeme|