Results 1 to 5 of 5
Hi all,
Why is this:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int i;
char *o;
} sr;
int main() {
sr *a;
a = (sr*)malloc(sizeof (sr));
a->i = 10;
...
- 06-03-2008 #1
free pointer to structur in C
Hi all,
Why is this:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int i;
char *o;
} sr;
int main() {
sr *a;
a = (sr*)malloc(sizeof (sr));
a->i = 10;
a->o = "Linux";
free(a);
printf("A after %d %s \n",a->i,a->o);
return 0;
}
the output of this program is 0 Linux, however printf is called after freeing the pointer!
if i switch the sr struct to
typedef struct {
char *o;
int i;
} sr;
so the output is 10 (null), like that free is always freeing the first element in the structure pointer to by a, the second element seems to remains in the mem.
?Linux is not only an operating system, it's a philosophy.
Archost.
- 06-03-2008 #2
Ideally they both should remain in memory until the operating system reclaims the freed memory.
- 06-03-2008 #3
free()ing memory does not mean you can no longer access it. It means that the memory is available for allocation the next time you do an explicit malloc() or realloc(). Part of that freed memory may be used (i.e., modified during the call to free()) in the bookkeeping of all returned (and not reused) chunks of main memory.
If you have a pointer to memory that has been freed, you should not use that pointer for anything, but that's entirely your responsibility. If you don't fulfill that responsibility properly, a delightful stretch of debugging awaits you, at the hour of its choosing (not yours).
Hope this helps.--
Bill
Old age and treachery will overcome youth and skill.
- 06-04-2008 #4Just Joined!
- Join Date
- May 2008
- Posts
- 2
free() is just free a head pointer to a series of space ,so you cannot access to
the first element.......but the element is still there...you can access them ...
- 06-04-2008 #5
a dangerous situation!
That's pretty much correct. Doing a free() on an array is likely to mangle only the first element of the array, and the following elements are accessible and likely to be their original content.free() is just free a head pointer to a series of space ,so you cannot access to
the first element.......but the element is still there...you can access them ...
But that's only reliable until you do another malloc() or realloc(), or some other library function which allocates space from the heap, such as strdup(). At that point, the leftover data may or may not be overwritten.
What makes this dangerous is that a program containing this bug (the bug being the accessing of free()d memory) may seem to work correctly, and then at random times it delivers incorrect data, perhaps only subtly incorrect.--
Bill
Old age and treachery will overcome youth and skill.


Reply With Quote