简体   繁体   中英

Debugging my program with Valgrind

My program runs correctly but when I analyze it with Valgrind I get an error:

 ==18865== Syscall param execve(argv) points to unaddressable byte(s) ==18865== at 0x513DCF7: execve (syscall-template.S:84) ==18865== by 0x513E50A: execvpe (execvpe.c:146) ==18865== by 0x406FE3: fork_pipes2 (util.c:1338) ==18865== by 0x40376A: execute_pipeline (main.c:282) ==18865== by 0x403E53: run_cmd (main.c:327) ==18865== by 0x403E53: command (main.c:668) ==18865== by 0x402722: main (main.c:870) ==18865== Address 0x589bb88 is 0 bytes after a block of size 8 alloc'd ==18865== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==18865== by 0x403E07: run_cmd (main.c:315) ==18865== by 0x403E07: command (main.c:668) ==18865== by 0x402722: main (main.c:870) ==18865==

The offending row is

pipe->data = malloc(sizeof(char*));

The code in context is

int run_cmd(char *cmd) {
    struct str_list *chunks = list_split(cmd, '|');
    struct pipeline *pipe = malloc(chunks->size * sizeof * pipe); 
    pipe->data =  malloc(sizeof(char*));
    int i=0;
    for (i= 0; i < chunks->size; i++) { /* TODO: factor out */;
        int j=0;
        for (j = 0; j < 1; j++) {
            pipe[i].data[j] = strdup(chunks[i].argv[j]);
        }
    }
    pipe->size = i;
    int status = execute_pipeline(pipe);
    return status;
}

My data structures:

struct str_list {
    char *name;
    int size;
    char **argv;

};
struct pipeline {
    char *name;
    int size;
    char **data;
};

Can you tell me why I get the error? I suppose I didn't use malloc correctly.

This allocation and these loops are wrong:

pipe->data =  malloc(sizeof(char*));
for (i= 0; i < chunks->size; i++) { /* TODO: factor out */;
    int j=0;
    for (j = 0; j < 1; j++) {
        pipe[i].data[j] = strdup(chunks[i].argv[j]);
    }
}

The allocation only allocate memory for the first pipes data member, not for the other in the array. You should allocate inside the outer loop, like

for (i= 0; i < chunks->size; i++) {
    pipe[i].data = malloc(sizeof(char *) * 1);

    for (int j = 0; j < 1; j++) {
        pipe[i].data[j] = strdup(chunks[i].argv[j]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM