Search code examples
clinuxunit-testingmemory-managementfunctional-testing

Host testing C program with hard coded memory addresses


We will write functional/unit tests for C code. This C program will be run as embedded software. However we need to run tests on a Linux environment.

The problem is that parts of the code under test looks like this:

my_addresses.h:

#define MY_BASE_ADDRESS     (0x00600000)
#define MY_OFFSET_ADDRESS   (0x108)

my_code.c

#include "my_addresses.h"

static const My_Type* my_ptr =
  (My_Type*)(MY_BASE_ADDRESS + MY_OFFSET_ADDRESS);

/* my_ptr is dereferenced and used ... */

Obviously, this will not run so well on Linux host environment.

Is there some way we can work around this issue during testing? Can we somehow "redirect" the program to use other addresses, that are valid addresses to memory allocated during test procedures?

Our first attempt was to replace "my_addresses.h" with another header file during tests, which (extern) declares variables instead of hard defines - then assign malloc'd memory to MY_BASE_ADDRESS, etc. The problem with that is the "static const" declaration in the c file. Of course you cannot assign a variable to a static const type.

Preferably, we should not modify the code under test (although in the worst case it may come to that).


Solution

  • You could check for e.g. the __linux__ macro and use conditional compilation. When on Linux use an array as base, and make it big enough to keep all the data needed in it.

    Something like e.g.

    #ifdef __linux__
    int8_t array[1024];
    # define MY_BASE_ADDRESS array
    #else
    # define MY_BASE_ADDRESS 0x00600000
    #endif