NanoP NanoP - 3 months ago 29
C Question

valgrind memcheck error allocating a string memory

Running my program, with I get this error :


==3205== Invalid write of size 8
==3205== at 0x40167C: push (load.c:75)
==3205== by 0x401725: load_tetrimino (load.c:112)
==3205== by 0x40112F: main (main.c:130)
==3205== Address 0x544e718 is 24 bytes after a block of size 16 in arena "client"
==3205==

valgrind: m_mallocfree.c:303 (get_bszB_as_is): Assertion 'bszB_lo ==
bszB_hi' failed. valgrind: Heap block lo/hi size mismatch: lo = 80, hi
= 88401728. This is probably caused by your program erroneously writing past the end of a heap block and corrupting heap metadata. If
you fix any invalid writes reported by Memcheck, this assertion
failure will probably go away. Please try that before reporting this
as a bug.

host stacktrace:
==3205== at 0x38082F78: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)
==3205== by 0x38083094: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)
==3205== by 0x38083221: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)
==3205== by 0x380909D4: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)
==3205== by 0x3807C683: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)
==3205== by 0x3807AF03: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)
==3205== by 0x3807F13A: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)
==3205== by 0x3807A49A: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)
==3205== by 0x38057FEE: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)
==3205== by 0x802C8C764: ???
==3205== by 0x802BA9F2F: ???
==3205== by 0x8020082CF: ???
==3205== by 0x401674: push (load.c:75)
==3205== by 0x8020082CF: ???
==3205== by 0x1BFF: ???
==3205== by 0x38C4F9FF: ???
==3205== by 0x804C2BFFF: ???
==3205== by 0x12C05: ???

sched status: running_tid=1

Thread 1: status = VgTs_Runnable (lwpid 3205)
==3205== at 0x401684: push (load.c:75)
==3205== by 0x401725: load_tetrimino (load.c:112)
==3205== by 0x40112F: main (main.c:130)


The piece of code :


int push(t_node **head, t_node **tail,

struct dirent *file)

{

t_node *new;

if ((new = malloc(sizeof(t_node *))) == NULL)

return (1);

if ((new->tetrimino.name = malloc(12 + my_strlen(file->d_name))) == NULL)

return (1);

exit(0);


Printing my_strlen(d_name) gives no error so it doesnt come from that

The structure :


typedef struct s_tetrimino

{

int id;

int sundial;

int color;

int height;

int width;

int end;

char **shape;

t_coord coord;

char *name;

} t_tetrimino;


Thanks

Answer

The allocation

new = malloc(sizeof(t_node *))

allocates memory for a node pointer, but this

new = malloc(sizeof(*new))

allocates memory for one node struct.

EDIT: As this code shows:

#include <stdio.h>

typedef struct {
    double a;
    double b;
    double c;
} t_node;

int main(void)
{
    t_node *new;
    printf("%zu\n", sizeof(t_node *));
    printf("%zu\n", sizeof(*new));
    return 0;
}

Program output (32 bit compiler)

4
24