Are you going through at some point and freeing each node in the list?
Linked list malloc memory leak
Question
I have the following struct
typedef struct Body
{
struct Body *next;
struct Body *prev;
SDL_Rect value;
} Body;
I want to allocate a new section of the body with the following
void init_body(Body **out_body, SDL_Rect *rect, Body *prev)
{
struct Body* new_body = malloc(sizeof(struct Body));
new_body->next = NULL;
new_body->prev = prev;
new_body->value = *rect;
*out_body = new_body;
}
However (i am on windows) Dr. Memory is making the following complaint:
Error #1: LEAK 24 direct bytes 0x02901b08-0x02901b20 + 0 indirect bytes
# 0 replace_malloc [d:\drmemory_package\common\alloc_replace.c:2292]
# 1 init_body [E:/Development/Projects/RipTide/main.c:61]
# 2 create [E:/Development/Projects/RipTide/main.c:75]
# 3 SDL_main [E:/Development/Projects/RipTide/main.c:213]
# 4 console_main [../src/main/windows/SDL_windows_main.c:140]
# 5 WinMain@16 [../src/main/windows/SDL_windows_main.c:177]
# 6 main [E:/Development/Projects/RipTide/main.c:263]
How do i go about cleaning up this memory leak?
And the logic for creat
void create(SDL_Renderer *renderer, Snake *snake) {
SDL_Rect r = SDL_CreateRect(10, 10, 100, 100);
snake->size = 1;
snake_init_body(&snake->body, &r, NULL);
snake->surf = SDL_CreateRGBSurface(0, 10, 10, 32, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF);
SDL_FillRect(snake->surf, NULL, 0xAAAAAAFF);
snake->texture = SDL_CreateTextureFromSurface(renderer, snake->surf);
}
DOH ended up needing to free later (and I never did):
void snake_free(Snake *snake)
{
struct Body *abody = snake->body;
while (abody != NULL)
{
if (abody->next == NULL)
{
free(abody);
break;
}
else
{
abody = abody->next;
}
if (abody != NULL)
free(abody->prev);
}
}
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow