diff --git a/libuavcan/src/protocol/uc_dynamic_node_id_allocation_server.cpp b/libuavcan/src/protocol/uc_dynamic_node_id_allocation_server.cpp index c358b80f88..55045e505a 100644 --- a/libuavcan/src/protocol/uc_dynamic_node_id_allocation_server.cpp +++ b/libuavcan/src/protocol/uc_dynamic_node_id_allocation_server.cpp @@ -228,10 +228,24 @@ int Log::initEmptyLogStorage() { MarshallingStorageDecorator io(storage_); - // Initializing last index + /* + * Writing the zero entry - it must always be default-initialized + */ + entries_[0] = protocol::dynamic_node_id::server::Entry(); + int res = writeEntryToStorage(0, entries_[0]); + if (res < 0) + { + return res; + } + + /* + * Initializing last index + * Last index must be written AFTER the zero entry, otherwise if the write fails here the storage will be + * left in an inconsistent state. + */ last_index_ = 0; uint32_t stored_index = 0; - int res = io.setAndGetBack(getLastIndexKey(), stored_index); + res = io.setAndGetBack(getLastIndexKey(), stored_index); if (res < 0) { return res; @@ -241,14 +255,6 @@ int Log::initEmptyLogStorage() return -ErrFailure; } - // Writing the zero entry - it must always be default-initialized - entries_[0] = protocol::dynamic_node_id::server::Entry(); - res = writeEntryToStorage(0, entries_[0]); - if (res < 0) - { - return res; - } - return 0; }