Search code examples
cstructmallocfreedevkitpro

Error when freeing elements of a struct depending on the order they are declared in C


I have the following struct:

typedef struct {
    char* json;
    char* jsonBody;
    char* tokens;
    int max_json_size;
    int max_num_tokens;
    int num_tokens;
} JsonResponse;

If I execute the following code everything works as expected:

JsonResponse* self = malloc(sizeof(self));
self->tokens = malloc(sizeof(self->tokens)*1024);
free(self->tokens);
free(self);

But the moment I assign the variable right below *tokens, in this case *max_json_size the code crashes, so for example this code would crash:

JsonResponse* self = malloc(sizeof(self));
self->tokens = malloc(sizeof(self->tokens)*1024);
self->max_json_size = 1024;
free(self->tokens); //crash here
free(self);

This only happens with the variable that is put right below the *tokens pointer in the struct, so in that example assigning the variable num_tokens works fine. If I move *tokens to the bottom of the struct everything seems to work fine too, but I'm afraid that it may be a time bomb. I thought about putting a "padding" int in the middle, that would probably solve the problem too.

But I'd like to know what am I doing wrong in this code, any help would be appreciated, I'm clueless. What is going on?

This is being programmed on a nintendo 3ds system in case it's relevant.


Solution

  • You are allocating the wrong size.

    JsonResponse* self = malloc(sizeof(self));
    

    You allocate the size of the pointer instead of the size of the buffers…