Skip to content

Memory leak when using WeakMap (heap grows despite GC) #5246

@FranckFreiburger

Description

@FranckFreiburger
Build platform

esp32 idf (5.4.1)

Test case
#include "jerryscript.h"
#include <stdio.h>
#include <string.h>
#include "assert.h"

void
app_main() {

	assert(jerry_feature_enabled(JERRY_FEATURE_HEAP_STATS));
    assert(jerry_feature_enabled(JERRY_FEATURE_WEAKMAP));

	const jerry_char_t script[] = 
	"var wm = new WeakMap();\n"
	"for (var i = 0; i < 1000; i++) {\n"
	"  wm.set({}, 1);\n"
	"}\n";

  jerry_init(JERRY_INIT_MEM_STATS );
  jerry_value_t parsed_code = jerry_parse(script, sizeof(script) - 1, NULL);

  jerry_heap_stats_t heapStats;
  jerry_heap_stats(&heapStats);
  printf("Heap allocated before: %zu\n", heapStats.allocated_bytes); // 424

  jerry_value_t run_val = jerry_run(parsed_code);
  jerry_value_free(run_val);

  jerry_heap_gc(JERRY_GC_PRESSURE_HIGH);

  jerry_heap_stats(&heapStats);
  printf("Heap allocated after: %zu\n", heapStats.allocated_bytes); // 8600

  jerry_value_free(parsed_code);
 
  jerry_cleanup();
}
Observed behavior

Example run:

Heap allocated before: 424
Heap allocated after: 8600

Even after forcing jerry_heap_gc(JERRY_GC_PRESSURE_HIGH), the allocated heap size remains significantly higher than before script execution.

Expected behavior

Since the keys passed to WeakMap.set are ephemeral object literals ({}) with no references kept outside, they should be eligible for garbage collection.
Memory usage should return close to the baseline after gc().

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions