Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying part of a string in C

Tags:

c

string

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.

like image 911
wolfPack88 Avatar asked Jun 08 '10 21:06

wolfPack88


People also ask

How can I copy just a portion of a string in C?

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.

What is strcpy in C?

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);

What is the difference between strcpy and strncpy?

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 .

Does strcpy overwrite?

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.


2 Answers

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.

like image 80
Pace Avatar answered Sep 30 '22 20:09

Pace


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

like image 29
Chris Dodd Avatar answered Sep 30 '22 21:09

Chris Dodd