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'.
stringafor NULL and handle accordingly (ie, only copy if not NULL)?strcpying from NULL is going to straight up crash on some systems. (i'm amazed it isn't on yours.) so you should just avoid doing that in the first place. like:if(stringa!=NULL) strcpy(string, stringa);strlen(NULL)is undefined behaviour. You must alter your logic to avoid calling this.malloc(),if (stringa == NULL) stringa = "";OTOH, what do you want if both areNULL?