Home > Mobile >  valgrind complains: Invalid write of size 8, On malloc
valgrind complains: Invalid write of size 8, On malloc

Time:11-01

I am not able to figure out, why I see this error while running Valgrind.

struct char_ctx {
    int  arr_size;
    char **char_array;
};

void char_compile() {

    struct char_ctx *ctx  = malloc(sizeof(struct char_ctx*));
    ctx->char_array = malloc((100) * sizeof(char *)); // I see error with this.
    char **y = malloc((100) * sizeof(char *)); // I dont see error with this.

    ctx->arr_size  = 100;
}

int main(int ac, char **av)
{
    
    char_compile();
    return 0;
}

Valgrind output

==30585== Invalid write of size 8
==30585==    at 0x108671: char_compile (temp.c:54)
==30585==    by 0x1086A8: main (temp.c:63)
==30585==  Address 0x522f048 is 0 bytes after a block of size 8 alloc'd
==30585==    at 0x4C31B0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==30585==    by 0x10865B: char_compile (temp.c:53)
==30585==    by 0x1086A8: main (temp.c:63)

The code executes properly. I see the error on ctx->char_array, but when I use char **y, I don't see the error.

CodePudding user response:

The problem is on this line:

struct char_ctx *ctx  = malloc(sizeof(struct char_ctx*));

You're only allocating space for a pointer to struct char_ctx, not a struct char_ctx. Because of this, a write to ctx->char_array writes past the end of allocated memory.

You instead want:

struct char_ctx *ctx  = malloc(sizeof(struct char_ctx));

Or better yet:

struct char_ctx *ctx  = malloc(sizeof *ctx);
  • Related