Say I had the following simple example
#include <stdlib.h>
#include <stdio.h>
struct x {
int* p;
};
typedef struct y {
x* foo;
}real;
void doSomething();
int main() {
doSomething();
getchar();
return 0;
}
void doSomething() {
real* tmp = (real*)malloc(sizeof(real));
tmp->foo = (x*)malloc(sizeof(x));
free(tmp->foo);
free(tmp);
}
Is it necessary to free the pointer I allocated inside before I free the "outer" allocated memory?
would the second line take care of the first allocated memory...my assumption is no(it will still remain on the heap I assume and I would need to keep it this way).
struct y, you refer to a typexbut, in C, that is not the type specified bystruct x. Only C++ defines the typexafter you definestruct x; C leaves the typexundefined until you usetypedef struct x x;. That means your code should not compile with a C compiler — but maybe you're using a C++ compiler to compile the code after all, despite the C tag. (Maybe the compiler is the MS Visual Studio compiler, at that.)malloc()andfree()— you usenewanddeleteif you aren't using types that take care of memory allocation automatically. If it is not C++ code, it doesn't compile. If it is C++ code, the casts on the results frommalloc()are necessary (assuming you usemalloc()at all); if it is C, you don't need the casts, though they don't do much harm if you're careful. Waaah!malloc()and family inC..