I am calling strdup to convert std::string to char * to pass as arguments for execvp. My doubt is, I never call free on that returned pointer. Is it a safe thing to do? Does it follow the best practices?
Code below:
std::string runCommand(const std::string &command) {
std::string result;
int fd[2];
if (pipe(fd) == -1) {
throw std::runtime_error("pipe() failed!");
}
pid_t pid = fork();
if (pid == -1) {
throw std::runtime_error("fork() failed!");
}
if (pid == 0) {
close(fd[0]); // Close read end
dup2(fd[1], STDOUT_FILENO); // Redirect stdout to pipe
dup2(fd[1], STDERR_FILENO); // Redirect stderr to pipe
close(fd[1]); // Close write end
// Convert command string into an array of arguments
std::vector<char*> args;
std::istringstream iss(command);
std::string token;
while (iss >> token) {
args.push_back(strdup(token.c_str())); // !! strdup - not freed later
}
args.push_back(nullptr);
execvp(args[0], args.data());
exit(EXIT_FAILURE); // exit child on failure
} else {
close(fd[1]); // Close write end
char buffer[1024];
ssize_t bytesRead;
while ((bytesRead = read(fd[0], buffer, sizeof(buffer) - 1)) > 0) {
buffer[bytesRead] = '\0'; // Null-terminate buffer
result += buffer;
}
close(fd[0]); // Close read end
waitpid(pid, nullptr, 0); // Wait for child to finish
}
return result;
}
[link] [comments]