TelluIoT / ThingML

The ThingML modelling language
https://github.com/TelluIoT/ThingML
Apache License 2.0
102 stars 32 forks source link

C/C++: a local array in functions is returned as a pointer #49

Closed vassik closed 8 years ago

vassik commented 10 years ago

Consider the following code in ThingML

function escape() : Byte[34]
do
    var escaped : Byte[34]
    escaped[0] = 0
    return escaped
end

and C generated code

uint8_t* f_Sender_escape(struct Sender_Instance *_instance) {
{
uint8_t escaped[34];
escaped[0] = 0;
return escaped;
}
}

Pointer to a local array is returned. Should never happen....

I would rather prefer dynamic allocation, but still not quite clear where to free this memory block...see below

uint8_t* f_Sender_escape(struct Sender_Instance *_instance) {
{
uint8_t* escaped = (uint8_t*) malloc(sizeof(uint8_t)*34);
escaped[0] = 0;
return escaped;
}
}
brice-morin commented 9 years ago

@Lyadis

nharrand commented 8 years ago

In my opinion this behaviour is not problematic. The range of your variable declared locally in a function should not extend the lifetime of the function. Therefore you should not allocate memory to it and not free it inside the same function.

If you want to modify the content of an array inside a function, the array should be passed as a parameter. In the same way if you want to allocate memory to your array and conserved it after the lifetime of the function, the variable should be declare outside of the function and passed as a parameter.