chain1 = (char *) malloc(5*sizeof(char*) + 1);
This will allocate enough space for five character pointers plus an extra byte. A pointer is not the same as a character, it tends to be either four or eight bytes currently but can actually be any size. You probably want sizeof(char)
but, since that’s always 1, you can just ignore it in multiplications.
You probably also want a number higher than five since that’s not even enough to store your fixed prefix.
In addition, the current content of that allocated block will be arbitrary so strcat
is not the first operation you should be performing on it (since that requires a valid C string).
This is almost certainly the cause of your “string starts with rubbish” problem. A strcpy
would be better as the first operation, or just use sprintf
to do the whole thing at once, rather than a strcpy/multiple-strcat
sequence.
And, finally, a command passed to system
does not need a trailing newline.
A better method may be something like:
static const char prefix[] = "cp mediaPlayer.exe ";
char *chain1 = malloc(sizeof(prefix) + strlen(actual->chain));
if (chain1 != NULL) {
sprintf(chain1, "%s%s", prefix, actual1->chain);
}
Space for the terminating \0
is accounted for my using sizeof
on the string rather than strlen
. The former includes space for the terminator. And note the check for a failed malloc
, this is something you should always do if you want robust code. I shouldn’t need to mention that, should chain1
end up being NULL
at the end of this code block, you should not pass it to system
.
solved Problem of a string read in function system() (probably due to a bad malloc) [closed]