C Keil compiler uses malloc for local variables,why?

Viewed 371

I had a problem somewhere in my code in a function that I wanted to declare an array but it failed. after some debugging I found out that it uses malloc in disassembly window so I increased the heap size and it works fine!

So my question is why keil uses Heap for local variable?

Here is the variable declaration code:

uint8_t result[data->capacityBytes];
memset(result, 0, sizeof(result));

I've added flag C99

2 Answers

Your array has a dynamic size, i.e. the compiler does not know how big it will be until runtime. This is a feature introduced in C99 called variable length arrays (VLA).

According to Keil's documentation (see the Note), such arrays are allocated on the heap by this compiler. (Others might allocate on the stack. Others might not implement this feature at all - it became optional in C11.)

Your local variable result is declared the following way:

uint8_t result[data->capacityBytes];

Assuming that data->capacityBytes is not a constant, that would mean that result would be a Variable Length Array (VLA), which would explain the behavior of the compiler you are using.

Then you are assuming that the variable location in memory zone is standardized, which is unfortunately incorrect, as described in this answer:

The C language does not define where any variables are stored, actually. It does, however, define three storage classes: static, automatic, and dynamic.

The location of where variable is stored is up to the interpretation of your source code by the compiler.

See also wikipedia entry about variable length array

Memory

Allocation

Related