Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a string into a char array in C++ without going over the buffer

Tags:

c++

string

char

g++

I want to copy a string into a char array, and not overrun the buffer.

So if I have a char array of size 5, then I want to copy a maximum of 5 bytes from a string into it.

what's the code to do that?

like image 430
neuromancer Avatar asked May 22 '10 19:05

neuromancer


People also ask

How do I copy a string into a char array?

Using c_str() with strcpy() A way to do this is to copy the contents of the string to the char array. This can be done with the help of the c_str() and strcpy() functions of library cstring.

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.

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 copy null terminator?

The strcpy() function copies string2, including the ending null character, to the location that is specified by string1. The strcpy() function operates on null-ended strings. The string arguments to the function should contain a null character (\0) that marks the end of the string.


2 Answers

This is exactly what std::string's copy function does.

#include <string>
#include <iostream>

int main()
{

    char test[5];
    std::string str( "Hello, world" );

    str.copy(test, 5);

    std::cout.write(test, 5);
    std::cout.put('\n');

    return 0;
}

If you need null termination you should do something like this:

str.copy(test, 4);
test[4] = '\0';
like image 98
CB Bailey Avatar answered Nov 11 '22 03:11

CB Bailey


First of all, strncpy is almost certainly not what you want. strncpy was designed for a fairly specific purpose. It's in the standard library almost exclusively because it already exists, not because it's generally useful.

Probably the simplest way to do what you want is with something like:

sprintf(buffer, "%.4s", your_string.c_str());

Unlike strncpy, this guarantees that the result will be NUL terminated, but does not fill in extra data in the target if the source is shorter than specified (though the latter isn't a major issue when the target length is 5).

like image 28
Jerry Coffin Avatar answered Nov 11 '22 04:11

Jerry Coffin