0

I've this code:

#include <stdio.h>
#include <unistd.h>
#include <json/json.h>
#include <stdio.h>

json_object *new_array;

void add_result_event(json_object *scan_result) {
    json_object_array_add(new_array, scan_result);
}


void add_scan_result() {
    json_object *scan_result = json_object_new_object();
    json_object_object_add(scan_result, "ssid", json_object_new_string("ssssssssssssssssssssssssssssiiiiiiiiiiiidddddddddd"));
    add_result_event(scan_result);
}

void alloc_object() {
    int i = 0;
    while (i < 100000) {
        add_scan_result();
        i++;
    }
}

int main() {
    new_array = json_object_new_array();
    printf(" not started.. see memory\n");
    system("ps -aux | grep sonj");
    sleep (1);

    alloc_object();
    printf(" allocated.. see memory\n");
    system("ps -aux | grep sonj");
    sleep (1);

    json_object_put(new_array);

    printf(" freed.. see memory\n");
    system("ps -aux | grep sonj");
    sleep (1);

    new_array  =  json_object_new_array();
    printf(" allocated.. see memory\n");
    alloc_object();
    system("ps -aux | grep sonj");
    sleep (1);
}

Compiled with:

~$ gcc json_array_obj_d.c -ljson-c -o sonj

Then, ran with:

~$ ./sonj

The VSZ field of output is not showing any memory freed to system after the json_object_put call.

So freeing with json_object_put does not give the memory to system, but next allocation also does not take more memory to system.

After json_object_put is called when the free memory shows up in system?

Azeem
  • 11,148
  • 4
  • 27
  • 40
  • `json_object_put` _decrements the reference count of_ `json_object` _and frees it if it reaches zero._ (See https://json-c.github.io/json-c/json-c-0.10/doc/html/json__object_8h.html). Further, the library may have internal object/memory management that does not necessarilly releases the storage to the heap, and neither does this imply the heap decreases (which is something else than "the system"). – Paul Ogilvie Oct 25 '17 at 12:13
  • Hello Paul, thanks for answer. But if the same experiment is done with malloc and free, ps -aux shows correct VSZ, ie it increases with alloc and decreases with free. That is also from heap. so only conclusion if json library eats memory but not gives to system. Seem like a dangerous idea. – debabrata pal Oct 25 '17 at 12:21
  • No, it does not necessarilly "eat" memory. The library may have internal memory management and a pool of object storage. Try allocating an object again and see wat happens to storage (maybe allocate a lot of objects and release them all, then do again and see how memory usage evolves). – Paul Ogilvie Oct 25 '17 at 12:30
  • Memory usage clamps to peak value ever used. After that new objects reuse memory hold by the process, even if none is used, the peak memory consumption never goes back to system. That is strange, huh? – debabrata pal Oct 26 '17 at 05:42

0 Answers0