J
Jack
how does free know how much of memory to release if I say free(ptr)?
Thanks.
Thanks.
Because it's good friends with malloc() and they share theJack said:how does free know how much of memory to release if I say free(ptr)?
Jack said:how does free know how much of memory to release if I say free(ptr)?
Jack said:how does free know how much of memory to release if I say free(ptr)?
Michael said:Your implementation does the book-keeping for everything you
allocated with malloc()/realloc()/calloc() or got from a
function using one of these. It then knows how much was
allocated -- and how much is to be free()d.
If you allocated storage for foo which in turn contains
a pointer bar and you allocate storage for bar, then
free()ing foo does not free() the storage bar points to.
Often, you can reach bar only via foo, so you have to
free(bar) before free(foo).
Jack said:Thanks a lot.
For example, if I define the following structure:
#include said:struct A {
int *a;
int b;
};
int main(){
int *c;
struct A *p = malloc(sizeof(struct A));
p->a = malloc(10*sizeof(int));
*(p->a) = 11;
*(p->a+1) = 22;
c = p->a;
printf("p->a: %d, p->a+1: %d, c+5: %d\n", *c, *(c+1), *(c+5));
free(p->a); //LINE1
free(p); //LINE2
}
Shoud I execute both LINE1 and LINE2, or only LINE2 is needed?
Michael said:malloc() can return a null pointer if not successful -- you
forgot to check for that:
if (NULL == p) {
fprintf(stderr, "%s, %d: Could not allocate storage for p\n",
__FILE__, __LINE__);
exit(EXIT_FAILURE);
};
p->a = malloc(10 * sizeof *p->a);
if (NULL == p->a) {
fprintf(stderr, "%s, %d: Could not allocate storage for p->a\n",
__FILE__, __LINE__);
free(p);
exit(EXIT_FAILURE);
};
c = p->a;
printf("p->a: %d, p->a+1: %d, c+5: %d\n", *c, *(c+1), *(c+5));
Note: You can also write c[0], c[1], c[5].
You did not assign a value to c[5] before reading from it, thus
the representation (the "bit pattern" in memory) could be one that
corresponds to no valid int.
Simon said:Why the extra semicolon here?
And here?
Just write p->a[0] = 11; and p->a[1] = 22;
Any time you find yourself adding to a pointer and then dereferencing
the result, it probably makes more sense to use square brackets.
c = p->a;
printf("p->a: %d, p->a+1: %d, c+5: %d\n", *c, *(c+1), *(c+5));
Note: You can also write c[0], c[1], c[5].
You did not assign a value to c[5] before reading from it, thus
the representation (the "bit pattern" in memory) could be one that
corresponds to no valid int.
In fact, you get undefined behaviour if you try to read a value from an
uninitialised memory location. The program may read a garbage value,
trap and/or crash.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.