ts2c icon indicating copy to clipboard operation
ts2c copied to clipboard

Incorrect generation of 'free' call

Open brunexgeek opened this issue 4 years ago • 0 comments

I changed the example of #74 from this

function return_from_obj(){
  let obj = {key:1};
  return obj.key;
}

console.log(return_from_obj());

to

let temp;

function return_from_obj(){
  let obj = {key:1};
  temp = obj;
  return obj.key;
}

console.log(return_from_obj());

and the corresponding output C code is

#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
typedef short int16_t;

struct temp_t {
    int16_t key;
};

static struct temp_t * temp;
int16_t return_from_obj()
{
    struct temp_t * obj;
    obj = malloc(sizeof(*obj));
    assert(obj != NULL);
    obj->key = 1;
    temp = obj;
    return obj->key;

}

int main(void) {
    printf("%d\n", return_from_obj());
    free(obj);

    return 0;
}

This C code has an error in free(obj), which should be free(temp). It appears the original variable name (obj in this case) is used to free the memory, even though the memory is referenced by another variable at that point.

I used the live demo for this test.

brunexgeek avatar Oct 19 '21 03:10 brunexgeek