How can I know if the memory address I'm reading from is empty or not in C++?

2.4k views Asked by At

So on an embedded system I'm reading and writing some integers in to the flash memory. I can read it with this function:

read(uint32_t *buffer, uint32_t num_words){
    uint32_t startAddress = FLASH_SECTOR_7;

    for(uint32_t i = 0; i < num_words; i++){
        buffer[i] = *(uint32_t *)(startAddress + (i*4));
    }
}

then

uint32_t buf[10];
read(buf,10);

How can I know if buff[5] is empty (has anything on it) or not?

Right now on the items that are empty I get something like this 165 '¥' or this 255 'ÿ'

Is there a way to find that out?

2

There are 2 answers

0
BufferOverflow On BEST ANSWER

You need first to define "empty", since you are using uint32_t. A good ide is to use value 0xFFFFFFFF (4294967295 decimal) to be the empty value, but you need to be sure that this value isn't used to other things. Then you can test if if ( buf [ 5 ] == 0xFFFFFFFF ).

But if your using the whole range of uint32_t, then there is no way to detect if it's empty.

Another way is to use structures, and define a empty bit.

struct uint31_t
{
    uint32_t empty : 0x01; // If set, then uint31_t.value is empty
    uint32_t value : 0x1F;
};

Then you can check if the empty bit is set, but the negative part is that you lose a whole bit.

6
Olivier Poulin On

If your array is an array of pointers you can check to see by comparing it to {nullptr}, otherwise, you cannot unless you initialize all the initial indexes to the same value, and then check if the value is still the same.