All in all, a very bad idea to use a system like this. system runs the command through the shell, which means that the line passed to system obeys all shell extensions, command extensions, special interpretation of characters, etc.
If you insist on using system , you should clear your line first. The easiest way to do this:
char *tmp = malloc(4*strlen(S)+3); tmp[0] = '\''; for (i=0,j=1; tmp[j]=S[i]; i++, j++) if (S[i]=='\'') tmp[++j]='\\', tmp[++j]='\'', tmp[++j]='\''; tmp[j++] = '\''; tmp[j++] = 0; if (snprintf(cmd, sizeof cmd, "foo %s ...", tmp) >= sizeof cmd) goto error; system(cmd);
This code selects the whole string S and replaces any embedded single quotes with '\'' . Please note that I also checked command line truncation in case this could lead to the execution of dangerous commands.
A better alternative would be to completely abandon system and execute your own fork and exec to get around the shell. Then there is no command line for interpretation; you have full control over the arguments ( *argv[] array) that are passed to the external program.
R ..
source share