Path: csiph.com!au2pb.net!feeder.erje.net!1.eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: I want to ask a question... Date: Fri, 07 Aug 2015 15:30:50 -0700 Organization: None to speak of Lines: 55 Message-ID: References: <87pp2y7wl7.fsf@gmail.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="945944de09706c9b4e29b53c9d2efdc2"; logging-data="22589"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/+uFg0YXRXHKNtyESZIl5C" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:WZcwVyqwMfngCYMjYfvzfXkXyHI= sha1:6xN5QBnQBoSkR1pW4gvy4hIxs7Y= Xref: csiph.com comp.lang.c:66977 Gareth Owen writes: > Ramine writes: >> Suppose that you are using a pointer that points to an allocated chunk >> of memory, and suppose that you deallocated this chunk of memory and >> you have keeped the old address of this pointer inside another pointer >> , is there a problem to access the old address of the pointer and >> content of the memory even if it was deallocated ? > > You can access the pointer itself, but you can't access the memory it > points to. Sometimes it might work - and it simple programs it probably > will work more ofhen than not - but you can't rely on it. > > Don't do that. That's not quite correct. Accessing a pointer value after the object it points to no longer exists has undefined behavior, even if you don't dereference it. It's not likely to do anything nasty on most systems, but in principle an implementation could mark the pointer value as invalid and trap on any reference to it. An example: #include #include int main(void) { int *p = malloc(sizeof *p); if (p == NULL) exit(EXIT_FAILURE); *p = 42; printf("p = %p\n", (void*)p); // OK printf("*p = %d\n", *p); // OK, prints 42 free(p); printf("p = %p\n", (void*)p); // Undefined behavior, *probably* won't crash printf("*p = %d\n", *p); // Undefined behavior, *probably* won't crash // The memory location may or may not have been clobbered. return 0; } Don't access either the pointer itself *or* the memory it points to. Of course a write access to the pointer object (such as assigning a new value to it) is fine, since it doesn't access the stored value. -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"