Re: Weird pointer error
From: Old Wolf (oldwolf_at_inspire.net.nz)
Date: 02/11/04
- Next message: David Tuman: "directory inventory"
- Previous message: Helium: "Re: Aspect Oriented Programming techniques"
- In reply to: Chris Mantoulidis: "Weird pointer error"
- Next in thread: Avinash: "Re: Weird pointer error"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 10 Feb 2004 15:05:58 -0800
> I see some really weird output from this program (compiled with GCC
> 3.3.2 under Linux).
> #include <iostream>
> using namespace std;
>
> int main() {
[snip code referring to "s2"]
> int *i;
> *i = 1;
[snip]
>
> return 0;
> }
>
> Output of the program is:
> Segmentation fault (what else, lol)
>
> I wrote this program because i wanted to see what happens when I
> assign values to pointers when I don't initialize them. If I comment
> out the s2 part, then the program works (no segfault).
>
> Why would s2 make this problem?
You caused UB with the "*i = 1" line. You should not be surprised
by any particular subsequent behaviour (including crashes,
failure to crash, and nasal demons).
The contents of your application's memory (which could determine
i's value before initialization) are affected by the other
allocations and function calls that you make.
You were (un) lucky in that without the s2 code, "i" happened to
point to memory that your platform thinks you are allowed to access,
and furthermore, memory that was not doing anything important,
so your antics did not cause the platform to complain.
> Oh, as I said, if I remove the s2 part it works fine and j's address
> is 4bytes before i (the pointer). So the compiler allocates memory
> with decreasing order? Or is this platform dependent?
Platform-dependent obviously. It could even give i and j the same address,
if they are never used concurrently, or they could not even have addresses
at all in some situations (eg. register variables)
Finally, you wrote:
> cout << "i = " << *i << " and &i " << &i << "\n";
>//could have used i instead of &i
You would get different results for "i" as for "&i"
(assuming you first fixed the UB).
- Next message: David Tuman: "directory inventory"
- Previous message: Helium: "Re: Aspect Oriented Programming techniques"
- In reply to: Chris Mantoulidis: "Weird pointer error"
- Next in thread: Avinash: "Re: Weird pointer error"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|