Liste des Groupes | Revenir à cl c |
On 22/11/2024 12:51, Waldek Hebisch wrote:Bart <bc@freeuk.com> wrote:>
int main(void) {
int a;
int* p = 0;
a = *p;
}
>
Here's what happens with my C compiler when told to interpret it:
>
c:\cx>cc -i c
Compiling c.c to c.(int)
Error: Null ptr access
>
Here's what happens with gcc:
>
c:\cx>gcc c.c
c:\cx>a
<crashes>
>
Is there some option to insert such a check with gcc? I've no idea; most
people don't.
I would do
gcc -g c.c
gdb a.out
run
and gdb would show me place with bad access. Things like bound
checking array access or overflow checking makes a big difference.
Null pointer access is reliably detected by hardware so no big
deal. Say what you 'cc' will do with the following function:
int
foo(int n) {
int a[10];
int i;
int res = 0;
for(i = 0; i <= 10; i++) {
a[i] = n + i;
}
for(i = 0; i <= 10; i++) {
res += a[i];
}
res;
}
Here gcc at compile time says:
foo.c: In function ‘foo’:
foo.c:15:17: warning: iteration 10 invokes undefined behavior [-Waggressive-loop-optimizations]
15 | res += a[i];
| ~^~~
foo.c:14:18: note: within this loop
14 | for(i = 0; i <= 10; i++) {
| ~~^~~~~
My 'cc -i' wouldn't detect it. The -i tells it to run an interpreter on
the intermediate code. Within the interpreter, some things are easily
checked, but bounds info on arrays doesn't exist. (The IL supports only
pointer operations, not high level array ops.)
That would need intervention at an earlier stage, but even then, the
design of C makes that difficult. First, because array types like
int[10] decay to simple pointers, and ones represented by types like
int* don't have bounds info at all. (I don't support int[n] params and
few people use them anyway.)
Les messages affichés proviennent d'usenet.