Re: Doubt on segmentation fault

Rainer Weikusat wrote:
Josef Moellers <josef.moellers@xxxxxxxxxxxxxx> writes:
char *a;
int i;

for (i=0; i<5; i++) {
a[i] = i;

return 0;

This process fails due to SIGSEGV. Here how kernel is creating
segmentation fault.

I'm thinking like cpu will look into tlb for finding address of 'a'
and since it's absent will look into page-table where page-table finds
that it's not an address belonging to this process, it
generates a segmentation fault.

Please correct if my understanding is wrong.
The address is not "absent", it's just ... sort of ... unspecified: as
you have not initialized "a", it will have whatever value was there

In this particular case, assuming the object is really allocated on
the stack, the value should always be zero. Otherwise, whatever the
last user of the corresponding page might have written to it would
become available to an unrelated process.

I'm not referring to a bug in the underlying OS (we all know THERE CANNOT BE ANY BUG IN LINUX ;-), but I was hinting at the fact that
- "main" may not be the first function ever called in this process (there may have been other helper-functions called before) or
- "a" is not allocated on the stack but rather in a processor register (as it would be on an x86_64 architecture) and this is what the loop looks like:
00000000004004d8 <main>:
4004d8: 48 83 ec 08 sub $0x8,%rsp
4004dc: ba 00 00 00 00 mov $0x0,%edx
4004e1: 48 63 c2 movslq %edx,%rax
4004e4: 88 14 30 mov %dl,(%rax,%rsi,1)
4004e7: ff c2 inc %edx
4004e9: 83 fa 04 cmp $0x4,%edx
4004ec: 7e f3 jle 4004e1 <main+0x9>
As you can see, it just uses %rsi as "a" and it has whatever value it had when "main" was entered.

In both cases, "a" may very well be non-0.

However, it may be 0 in some cases and I have not ruled out those cases.

These are my personal views and not those of Fujitsu Technology Solutions!
Josef Möllers (Pinguinpfleger bei FTS)
If failure had no penalty success would not be a prize (T. Pratchett)
Company Details: