0

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.

Aridez
  • 452
  • 5
  • 17

1 Answers1

0

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…

  • 1
    For the same reason, `self->tokens = malloc(sizeof(self->tokens)*1024);` is also allocating the wrong size, although it is allocating too much space (space for 1024 pointers) rather than not enough space. (I'm assuming `sizeof(char*) > sizeof(char)`.) – Ian Abbott Oct 15 '18 at 14:01