Advertisement
Guest User

Untitled

a guest
Jan 21st, 2020
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. struct foo {
  2. void *data;
  3. };
  4.  
  5. struct foo *foo_new (void) {
  6. struct foo *self = (struct foo *)malloc(sizeof(*self));
  7.  
  8. self->data = NULL;
  9.  
  10. return self;
  11. }
  12.  
  13. void foo_set (struct foo *self, void *data, size_t l_data) {
  14. free(self->data);
  15. self->data = (void *)malloc(l_data);
  16. memcpy(self->data, data, l_data);
  17. }
  18.  
  19. void foo_free (struct foo *self) {
  20. free(self->data);
  21. free(self);
  22. }
  23.  
  24. struct bar {
  25. void *always_allocated;
  26. };
  27.  
  28. struct bar *bar_new (void) {
  29. struct bar *self = (struct bar *)malloc(sizeof(*self));
  30.  
  31. self->always_allocated = (void *)malloc(0);
  32.  
  33. return self;
  34. }
  35.  
  36. void bar_free (struct bar *self) {
  37. free(self->always_allocated);
  38. free(self);
  39. }
  40.  
  41. int main () {
  42. struct foo *f = foo_new();
  43.  
  44. /* This would loose track of the original pointer and allocate new memory.
  45. * foo_free wouldn't call bar_free, but the "generic" free function.
  46. *
  47. * How would I correctly store my struct bar inside my struct foo without having memory leaks?
  48. **/
  49. foo_set(f, bar_new());
  50.  
  51. foo_free(f);
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement