Posts Tagged ‘data-types’

Introduction to Erlang : Basic Types (2/2)

This entry is part 5 of 16 in the series Introduction to Erlang

More Data Types

Today we will see some more sophisticated Erlang’s data types; tuple, list, and fun.

Tuple

Tuple is a compound data type; it consists of elements of any data type. A tuple has the form:

{Element1, Element2, ..., ElementN}

where N is called the size the tuple.

1> {1,2}.
{1,2}
2> {true, {value, whatever}}.
{true,{value,whatever}}
3> {1, a, 1.1, {{{{4}}}}}.
{1,a,1.1,{{{{4}}}}}
4> is_tuple({}). % built-in function (BIF)
true
5> element(3, {1,2,3}). % the element at position 3
3
6> size({1,2,3}).% the size of the tuple
3

Read the rest of this entry »

Introduction to Erlang : Basic Types (1/2)

This entry is part 4 of 16 in the series Introduction to Erlang

Command Terminator

Erlang uses a simple dot (.) as the command terminator. Consequently every correct Erlang statement should terminate with a dot.

1> 1
1> 2.
* 2: syntax error before: 2
1> 1.
1
2> 2.
2

The Most Basic Types

I will introduce the data types of Erlang and the basic operations on them by example. Most of the material presented today will look familiar to other programming languages. The next post will present some more sophisticated data types.
Read the rest of this entry »

Structures and Memory Consumption in C

Motivation

The way you design you structures in C can have a (significant) impact on the size they occupy in memory!

Memory structure of a structure

A structure occupies contiguous space in memory. Though, in order to provide efficient access to the structure’s fields, C uses padding. In other words, the fields are aligned to the memory words.

Example

In a system with:

  • word : 4 bytes
  • char : 1 byte
  • int : 4 bytes

without padding would be:

char (8bit) int (32bit)

and since the word size is 4 bytes the integer would belong to 2 different words, so in order to access it, two memory accesses would be necessary.
In order to avoid it, the actual memory organization is:

char (8bit) padding (24bit) int (32bit)

The Possible Problem

A bad designed structure can possible occupy more space than needed.

Example

Take a look at the following structure:

struct bad {
  char c1;
  int i1;
  char c2;
};

One would possibly say that since 1 + 4 + 1 = 6 bytes is the total size of the fields, 2 words = 8 bytes will be needed to store it. This is not true. Due to the padding we have:

c1 (8bit) padding (24bit) i1 (32bit) c2 (8bit) padding (24bit)

3 words = 12 bytes, 4 more bytes than necessary.

Solution

Just take into account how the types fit together:

struct good {
  char c1; //c1 + c2 = 2 bytes
  char c2;
  int i1;
};

This design needs the minimum number of 2 words = 8 bytes.

Outcome

The bigger the structure gets, the more space you can lose.. So, take care of it while designing the structures!