This seems like it should be really simple, but for some reason, I'm not getting it to work. I have a string called seq, which looks like this:
ala
ile
val
I want to take the first 3 characters and copy them into a different string. I use the command:
memcpy(fileName, seq, 3 * sizeof(char));
That should make fileName = "ala"
, right? But for some reason, I get fileName = "ala9"
. I'm currently working around it by just saying fileName[4] = '\0'
, but was wondering why I'm getting that 9.
Note: After changing seq to
ala
ile
val
ser
and rerunning the same code, fileName becomes "alaK"
. Not 9 anymore, but still an erroneous character.
Using the inbuilt function strcpy() from string. h header file to copy one string to the other. strcpy() accepts a pointer to the destination array and source array as a parameter and after copying it returns a pointer to the destination string.
strcpy() is a standard library function in C/C++ and is used to copy one string to another. In C it is present in string. h header file and in C++ it is present in cstring header file. Syntax: char* strcpy(char* dest, const char* src);
The strcpy function copies string str2 into array str1 and returns the value of str1 . On the other hand, strncpy copies the n characters of string str2 into array str1 and returns the value of str1 .
The strcpy() function does not stop until it sees a zero (a number zero, '<0') in the source string. Since the source string is longer than 12 bytes, strcpy() will overwrite some portion of the stack above the buffer. This is called buffer overflow.
C uses a null terminator to denote the end of a string. memcpy doesn't know that you're copying strings (it just copies bytes) so it doesn't think to put one on. The workaround you have is actually the right answer.
Edit: wolfPack88 has a good point. You really need to be changing filename[3]. Also, the below comments bring up some great points about strncpy which is a choice worth learning too.
sprintf is your friend for extracting characters from the middle of one string and putting them in a character buffer with null termination.
sprintf(fileName, "%.3s", seq);
or
sprintf(fileName, "%.*s", 3, seq);
or even
snprintf(fileName, sizeof(fileName), "%.*s", len, seq);
will give you what you want. The *
version allows a variable length, and snprintf
is safer for avoiding buffer overflows
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With