Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct foo {
- void *data;
- };
- struct foo *foo_new (void) {
- struct foo *self = (struct foo *)malloc(sizeof(*self));
- self->data = NULL;
- return self;
- }
- void foo_set (struct foo *self, void *data, size_t l_data) {
- free(self->data);
- self->data = (void *)malloc(l_data);
- memcpy(self->data, data, l_data);
- }
- void foo_free (struct foo *self) {
- free(self->data);
- free(self);
- }
- struct bar {
- void *always_allocated;
- };
- struct bar *bar_new (void) {
- struct bar *self = (struct bar *)malloc(sizeof(*self));
- self->always_allocated = (void *)malloc(0);
- return self;
- }
- void bar_free (struct bar *self) {
- free(self->always_allocated);
- free(self);
- }
- int main () {
- struct foo *f = foo_new();
- /* This would loose track of the original pointer and allocate new memory.
- * foo_free wouldn't call bar_free, but the "generic" free function.
- *
- * How would I correctly store my struct bar inside my struct foo without having memory leaks?
- **/
- foo_set(f, bar_new());
- foo_free(f);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement