0%

How to reduce the memory size of the code

You don’t care memory size in PC but it is small in the embedded system. This post shows a couple of simple ways to reduce the wasted memory in your code.

  • Use dynamic allocation
  • Don’t use global variable
  • Refactoring your code
  • How to calculate memory size

Use dynamic allocation

Static variables use many memory sizes until the program exits. You should use dynamic allocation if you don’t use as the same as memory each time or you don’t use the variables again.

Don’t use global variable

Compare the memory size with global variable and local variable. global variable use more memory size because the variable alives when the program begins.

global.c

1
2
3
4
5
6
7
8
9
10
int size[10000];
int main()
{
memset(size, 0x0, sizeof(size));
return 0;
}

$ size global
__TEXT __DATA
4096 40960

local.c

1
2
3
4
5
6
7
8
9
int main()
{
int size[10000];
memset(size, 0x0, sizeof(size));
return 0;
}
$ size local
__TEXT __DATA
4096 4096

Refactoring your code

You should refactor your code many times. You can find out many code that can use as the same as the function and variable.

How to calculate memory size

Let’s talking more details about stack and heap and something else.

  • What is stack
  • What is heap
  • What is .bss and .data and .text

stack [1]

The stack area contains the program stack, a LIFO structure, typically located in the higher parts of memory. When call function, local variable will put into stack until the function exits. If you write a recursive function, it use many stacks.

Please following the code that use 40 bytes until function ‘run1’ exits.

1
2
3
4
5
6
7
void run2() {
u16 num[10];
}
void run1() {
u16 num[10];
run2();
}

heap [1]

The heap area commonly begins at the end of the .bss and .data segments and grows to larger addresses from there. The heap area is managed by malloc, calloc, realloc, and free, which may use the brk and sbrk system calls to adjust its size

Please following the code that use 10 bytes until free the variable ‘str’.

1
2
3
4
5
6
void run3() {
void *str;
str = malloc(sizeof(u8) * 10);
//...
free(str);
}

What is .bss and .data

.bss [1]

The BSS segment, also known as uninitialized data, is usually adjacent to the data segment. The BSS segment contains all global variables and static variables that are initialized to zero or do not have explicit initialization in source code.

.data [1]

The .data segment contains any global or static variables which have a pre-defined value and can be modified.

.text [1]

The code segment, also known as a text segment or simply as text, is where a portion of an object file or the corresponding section of the program’s virtual address space that contains executable instructions is stored and is generally read-only and fixed size.