Invalid read of size 8/ Syscall param execve(argv) points to unaddressable byte(s)
I spent the last few days lookin for the problem but I couldn't find it. the program is an attempt to create a simple shell. this is the error message that I'm getting:
> ==389== Invalid read of size 8
> ==389== at 0x10B9C0: executor (shell.c:1696)
> ==389== by 0x10BC3E: main (shell.c:1773)
> ==389== Address 0x1ffefffad0 is on thread 1's stack
> ==389== 784 bytes below stack pointer
> ==389==
> ==389== Syscall param execve(argv) points to unaddressable byte(s)
> ==389== at 0x49620FB: execve (syscall-template.S:120)
> ==389== by 0x10BA0B: executor (shell.c:1702)
> ==389== by 0x10BC3E: main (shell.c:1773)
> ==389== Address 0x1ffefffad0 is on thread 1's stack
> ==389== 776 bytes below stack pointer
This is the executor function, I tried using gdb with valgrind and I managed to pinpoint exactly when the invalid read of size 8 occurs. it occurs at this line
pid_t pid = fork();
void executor(const CommandArgs *args)
{
pid_t pid = fork();
char *cmd_p;
if (pid == -1)
{
perror("failed to fork");
exit(EXIT_FAILURE);
}
else if (pid == 0)
{
cmd_p = pathfinder(args->data[0]);//line 1696
if (cmd_p == NULL)
{
perror("Error");
exit(EXIT_FAILURE);
}
execve(cmd_p, args->data, environ); //line 1702
perror("execve");
exit(EXIT_FAILURE);
}
else
{
wait(NULL);
}
}
i think that the pathfinder function is the source of the problem so here it is
char* pathfinder(char* cmd)
{
static char path[MAX_PATH_LEN];
static char p_token[MAX_PATH_LEN];
static char p_file[MAX_FILE_LEN];
static char result[MAX_FILE_LEN];
char *token, *path_ptr;
struct stat buff;
char* env_path = _getenv("PATH");
if (env_path)
{
_strncpy(path, env_path, sizeof(path));
path[sizeof(path) - 1] = '\0';
path_ptr = path;
token = _strtok_r(path_ptr, ":", &path_ptr);
while (token != NULL)
{
_strncpy(p_token, token, sizeof(p_token));
p_token[sizeof(p_token) - 1] = '\0';
_strncpy(p_file, p_token, sizeof(p_file));
p_file[sizeof(p_file) - 1] = '\0';
_strncat(p_file, "/", sizeof(p_file) - _strlen(p_file) - 1);
_strncat(p_file, cmd, sizeof(p_file) - _strlen(p_file) - 1);
if (stat(p_file, &buff) == 0)
{
_strncpy(result, p_file, sizeof(result));
result[sizeof(result) - 1] = '\0';
return result;
}
token = strtok_r(path_ptr, ":", &path_ptr);
}
}
if (stat(cmd, &buff) == 0)
{
_strncpy(result, cmd, sizeof(result));
result[sizeof(result) - 1] = '\0';
return result;
}
return NULL;
}
I hope someone helps me with more insight