Path: news.eternal-september.org!eternal-september.org!feeder3.eternal-september.org!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: =?UTF-8?Q?Josef_M=C3=B6llers?= Newsgroups: comp.lang.c Subject: Re: Memory protection between compilation units? Date: Wed, 11 Jun 2025 16:06:10 +0200 Lines: 48 Message-ID: References: <20250611153239.6bc43323@mateusz> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit X-Trace: individual.net WVzQ2S2t1uDPdl0W1j/GAgzxA5vPd9GbOWoWGZdadEs/o0MD8y Cancel-Lock: sha1:aq2ayr8LjyZMM0qX8vI+k7uL560= sha256:pQfnLR02Oxyu5Y26dPryKMn+ZZqxBJIXpRhOYABGwU8= User-Agent: Mozilla Thunderbird Content-Language: en-US In-Reply-To: <20250611153239.6bc43323@mateusz> On 11.06.25 15:32, Mateusz Viste wrote: > 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. The pointer was allocated immediately behind the "socks" array, i.e. as the 0x10000th element of the array (I have analyzed a similar problem for our son a couple of years ago, where the problem occurred and vanished when he added some debug statements ;-) ). > 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. I guess it can't because modules can access variables from other modules, so either you forbid module B to modify a variable from module A, which would break almost every moderately complex program, or you fall into this trap. Thus said ... this is not a problem of memory protection but a problem of an out-of-bounds programming error. And ... no, you can't forbid this as well, as there are quite a number of programs that define a variable-length array (usually in a structure) as having a size of 1 and happily writing to index 1234. > How would you approach this? Difficult, but, as I said, it's a programming error. Josef