0

Periodically in C I have errors which I believe come from an error in my code causing data to be corrupted, possibly by writing an array using a size which is too larger so flowing over allocated memory into other variables. I find this very painful to debug but figure it must be a common problem so maybe there are better approaches.

My current approach is to put print statements to print the value stored at the offending address throughout my code to figure out where it is getting overwritten. Are there better was to go about it? I have tried putting a breakpoint on that memory address but somehow it doesn't trigger.

An example is shown below - results will of course depend on the compiler.

PLEASE NOTE - code below has error by design to illustrate the sort of issue I am trying to debug.

uint16_t array_a[256];
uint8_t array_b[256];

void main()
{
    array_a[4] = 0;
    printf("Before: array_a[4] = %u\n", array_a[4]);
    // Intentionally write to memory beyond end of array_b to illustrate issue.
    for (uint16_t k=0;k<266;k++)
    {
        array_b[k] = k;
    }
    printf("After: array_a[4] = %u\n", array_a[4]);
    getch();
}

Output:

Before: array_a[4] = 0
After: array_a[4] = 2312

So although I haven't explicitly touched array_a, its values have changed in my loop. Easy to debug here, but this soon gets pretty complicated when code in one class is affecting variables in another!

bgarrood
  • 419
  • 8
  • 17

0 Answers0