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);
}

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.