Reputation: 255
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.
Upvotes: 1
Views: 416
Reputation: 409404
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]);
}
}
Upvotes: 1