From 933c15c6417cd6f032c0d6f1a6eabd86a17d0d82 Mon Sep 17 00:00:00 2001 From: "Tse-Chia.Chang" Date: Tue, 7 May 2024 17:45:49 +0800 Subject: [PATCH] Ensure superblock always fits SIMPLEFS_BLOCK_SIZE In current implementation, the struct superblock used padding via subtraction to match the SIMPLEFS_BLOCK_SIZE, which could lead to the need for recalculating the padding when the data structure changed. This commit uses union to set struct superblock size and uses _Static_assert macro to check the size. --- mkfs.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/mkfs.c b/mkfs.c index 16e4029..c47f561 100644 --- a/mkfs.c +++ b/mkfs.c @@ -11,8 +11,10 @@ #include "simplefs.h" struct superblock { - struct simplefs_sb_info info; - char padding[4064]; /* Padding to match block size */ + union { + struct simplefs_sb_info info; + char padding[SIMPLEFS_BLOCK_SIZE]; /* Padding to match block size */ + }; }; /** @@ -237,6 +239,7 @@ static int write_data_blocks(int fd, struct superblock *sb) int main(int argc, char **argv) { + _Static_assert(sizeof(struct superblock) == SIMPLEFS_BLOCK_SIZE); if (argc != 2) { fprintf(stderr, "Usage: %s disk\n", argv[0]); return EXIT_FAILURE;