Reputation: 11
I have the following code:
char *string = malloc(strlen(stringa) + strlen(stringb) + 1);
strcpy(string, stringa);
strcpy(string+strlen(stringa), stringb);
the problem is, with what I'm doing, stringa
is sometimes NULL, and when it is and it gets copied to string
, it results in uninitialized characters at the very beginning of string
. Here's an example of the output that I am getting when stringa happens to be NULL:
�����o
This is a test
To see the output
of string
I want to get rid of the characters at the beginning that are uninitialized. What I tried doing so far is:
memset(string, 0, strlen(string));
and
memset(string, 0, sizeof(string));
both have given me errors and do not solve my problem. Anyone know how I could edit 'string' to get rid of the uninitialized characters? This could either be applied to 'string' directly or to 'stringa' before it gets copied to 'string'.
Upvotes: 0
Views: 139
Reputation: 6404
In very old C, on many platforms, a nul byte happened to be hardcoded to location zero in memory, and so there wasn't a distinction between the null string and the empty string. It's a bit of an odd difference if you think of it, no string of sausages versus a string of no sausages.
You can easily resurrect the old behaviour, by wrapping strcpy
char *strcpy_oldbehaviour(char *dest, const char *src)
{
if(src)
return strcpy(dest, src);
else
return strcpy(dest, "");
}
Upvotes: 0
Reputation: 7742
You can always run some logical tests with a conditional statement on the value of the strings before you begin copying them:
Option 1:
char* string;
size_t length = 0;
if (stringa != NULL) {
length += strlen(stringa);
}
if (stringb != NULL) {
length += strlen(stringb);
}
string = malloc(length + 1);
// Copy the strings
Option 2:
char* string = NULL;
if (stringa != NULL) {
string = malloc(strlen(stringa) + 1);
strcpy(string, stringa);
}
if (stringb != NULL) {
if (string != NULL) {
string = realloc(string, strlen(stringb) + 1);
strcat(string, stringb);
} else {
string = malloc(strlen(stringb) + 1);
strcpy(string, stringb);
}
}
Upvotes: 1