Path: news.eternal-september.org!eternal-september.org!.POSTED!not-for-mail From: Mikko Newsgroups: comp.lang.c Subject: Re: Memory protection between compilation units? Date: Thu, 12 Jun 2025 11:40:20 +0300 Organization: - Lines: 39 Message-ID: <102e3pk$2j4ts$1@dont-email.me> References: <20250611153239.6bc43323@mateusz> MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 8bit Injection-Date: Thu, 12 Jun 2025 10:40:20 +0200 (CEST) Injection-Info: dont-email.me; posting-host="895999819a5c78832fa7d733efdcd182"; logging-data="2724796"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/PaiosZ0G6jbEc32NxUrxo" User-Agent: Unison/2.2 Cancel-Lock: sha1:pDp8h3nlLlJrPe/e8SRqI7HzTxE= On 2025-06-11 13:32:39 +0000, Mateusz Viste said: > This might not be a strictly C question, but it definitely concerns all > C programmers. > > Earlier today, I fixed an out-of-bounds write bug. An obvious issue: > > static int *socks[0xffff]; > > void update_my_socks(int *sock, int val) { > socks[val & 0xffff] = sock; > } > > While the presented issue is common knowledge for anyone familiar with > C, *locating* the bug was challenging. The program did not crash at the > moment of the out-of-bounds write but much later - somewhere entirely > different, in a different object file that maintained a static pointer > for tracking a position in a linked list. To my surprise, the pointer > was randomly reset to NULL about once a week, causing a segfault. > Tracing this back to an unrelated out-of-bounds write elsewhere in the > code was tedious, to say the least. > > This raises a question: how can such corruptions be detected sooner? > Protected mode prevents interference between programs but doesn’t > safeguard a program from corrupting itself. Is there a way to enforce > memory protection between module files of the same program? After all, > static objects shouldn't be accessible outside their compilation unit. > > How would you approach this? The traditional method to ensure that a program or a part of a program does not do what it must not do is testing. In this case the tester must modify the code so that the array socks is a part of a larger data structure and and call update_my_socks with different values for val, including the critical values -1, 0, 0xfffe, and 0xffff. -- Mikko