Hi, i am new to c/c++ and i need to execute external cabextract program to extract archive, but if i sprintf command and file name to command variable i get segmentation fault. How i need to modify code to avoid segmentation fault?

Here's an example:

void cabext(const char *fname)
{
	char *command;
	sprintf(command,"cabextract -L -d /tmp/ %s",fname);
	system(command);
}

int main() {
	const char *fname = "/home/me/archive.cab";
	cabext(fname);
}

Dani AI

Generated

The crash happens because command in the original function is an uninitialized pointer and sprintf writes into whatever memory that pointer happens to reference. is correct that allocating storage fixes the immediate segfault, but there are safer and more robust approaches to recommend for real code.

A simple, idiomatic C++ fix is to build the command with std::string and pass its C string to system (no manual allocation or fixed-size buffers):

#include <string>
#include <cstdlib>

std::string cmd = std::string("cabextract -L -d /tmp/ ") + fname;
int rc = system(cmd.c_str());

If a C-style buffer is required, use snprintf and resize dynamically to avoid overflow rather than sprintf:

#include <vector>
#include <cstdio>

std::vector<char> buf(256);
int n = std::snprintf(buf.data(), buf.size(), "cabextract -L -d /tmp/ %s", fname);
if (n >= (int)buf.size()) {
    buf.resize(n + 1);
    std::snprintf(buf.data(), buf.size(), "cabextract -L -d /tmp/ %s", fname);
}
system(buf.data());

Important security note: system() runs a shell, so if fname can contain untrusted data it can lead to shell injection. To avoid that, invoke the program directly (no shell) using fork + execlp / execv / posix_spawn so arguments are passed safely:

#include <unistd.h>
#include <sys/wait.h>

pid_t pid = fork();
if (pid == 0) {
    execlp("cabextract", "cabextract", "-L", "-d", "/tmp/", fname, (char*)NULL);
    _exit(127);
}
int status;
waitpid(pid, &status, 0);

Checklist: avoid sprintf, prefer snprintf or std::string, validate or sanitize fname, check return codes, and prefer exec-style calls over system() when input might be untrusted. This keeps the program safe and avoids the allocation/overflow bugs that caused the segfault reported by .

Recommended Answers

All 2 Replies

line 3 does not allocate any memory for that array and sprintf() doesn't allocate it either.

void cabext(const char *fname)
{
	char command[1024] = {0};
	sprintf(command,"cabextract -L -d /tmp/ %s",fname);
	system(command);
}
commented: Yes indeed. +17

Thank you :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.