Questions tagged [strncpy]

A C standard library function: strncpy is used to copy a maximum of n characters of non-overlapping, fixed-width or null-terminated strings. Defined also as std::strncpy in C++ standard library.

Used to copy a maximum of n characters of non-overlapping, fixed-width or null-terminated strings. It is defined in the <string.h> C standard header or the <cstring> C++ standard header.

This function is not recommended to use for any purpose, neither in C nor C++. It was never intended to be a "safe version of strcpy" but is often misused for such purposes. It is in fact considered to be much more dangerous than strcpy, since the null termination mechanism of strncpy is not intuitive and therefore often misunderstood. This is because of the following behavior specified by ISO 9899:2011 7.24.2.4:

char *strncpy(char * restrict s1, 
     const char * restrict s2, 
     size_t n);

/--/

3 If the array pointed to by s2 is a string that is shorter than n characters, null characters are appended to the copy in the array pointed to by s1, until n characters in all have been written.

A very common mistake is to pass an s2 which is exactly as many characters as the n parameter, in which case s1 will not get null terminated. That is: strncpy(dst, src, strlen(src));

/* MCVE of incorrect use of strncpy */
#include <string.h>
#include <stdio.h>

int main (void)
{
  const char* STR = "hello";
  char buf[] = "halt and catch fire";
  strncpy(buf, STR, strlen(STR));
  puts(buf); // prints "helloand catch fire"
  return 0;
}

Recommended practice in C is to check the buffer size in advance and then use strcpy(), alternatively memcpy(). Recommended practice in C++ is to use std::string instead.

References:
- ISO/IEC 9899:2011 Information technology — Programming languages — C. Chapter 7.24.2.4.
- Why are strlcpy and strlcat considered insecure?
- What are the C functions from the standard library that must / should be avoided?

Documentation:
C strncpy documentation.
C++ std::strncpy documentation.

253 questions
7
votes
4 answers

Copy end of string in C

I am trying to use strncpy to only copy part of a string to another string in C. Such as: c[] = "How the heck do I do this"; Then copy "do this" to the other string, such that: d[] = "do this" Help is appreciated.
Church
  • 115
  • 2
  • 3
  • 11
7
votes
7 answers

strncpy and using sizeof to copy maximum characters

I am using the code below char call[64] = {'\0'} /* clean buffer */ strncpy(call, info.called, sizeof(call)); I always use the sizeof for the destination for protecting a overflow, incase source is greater than the destination. This way I can…
ant2009
  • 27,094
  • 154
  • 411
  • 609
6
votes
6 answers

strncpy documentation question

At the following regarding strncpy: http://www.cplusplus.com/reference/clibrary/cstring/strncpy/, it mentions the following: No null-character is implicitly appended to the end of destination, so destination will only be null-terminated if the…
Simplicity
  • 47,404
  • 98
  • 256
  • 385
5
votes
5 answers

traversing C string: get the last word of a string

how would you get the last word of a string, starting from the '\0' newline character to the rightmost space? For example, I could have something like this where str could be assigned a string: char str[80]; str = "my cat is yellow"; How would I…
user1000219
  • 115
  • 1
  • 2
  • 6
5
votes
1 answer

strncpy implementation too complicated in glibc

I'm trying to understand string.h functions. Here is my own implementation of strncpy() char * my_strncpy(char *dst, const char* src, int n) { char *orig = dst; const char *hold = src; int count = 0, remain = 0; while(*(hold++)) …
Siva Padhy
  • 99
  • 6
5
votes
2 answers

Copy length of characters from array to std::string

I am trying to copy 5 characters from a character array into a std::string char name[] = "Sally Magee"; std::string first; copy(name, name + 5, first.begin()); //from #include std::cout << first.c_str(); However I get the string plus a…
user2537688
  • 87
  • 1
  • 5
4
votes
6 answers

strncpy doesn't always null-terminate

I am using the code below: char filename[ 255 ]; strncpy( filename, getenv( "HOME" ), 235 ); strncat( filename, "/.config/stationlist.xml", 255 ); Get this message: (warning) Dangerous usage of strncat - 3rd parameter is the maximum number of…
user1840007
  • 615
  • 1
  • 10
  • 19
4
votes
3 answers

Using strncpy. Valgrind throws invalid read

I made this function: void procesar_llamadaAFuncion(t_proceso *unProceso, char *sentencia){ char *nombreFuncion = sentencia; char *nombreFuncionSinParentesis = NULL; string_trim(&nombreFuncion); nombreFuncionSinParentesis =…
4
votes
4 answers

Creating C substrings: looping with assignment operator VS strncopy, which is better?

This might be somewhat pointless, but I'm curious what you guys think about it. I'm iterating over a string with pointers and want to pull a short substring out of it (placing the substring into a pre-allocated temporary array). Are there any…
groundlar
  • 878
  • 1
  • 8
  • 17
4
votes
3 answers

Weird behavior with stack and heap while using strncpy

I found a very interesting question. When I'm using following code: int main() { char * in = "hi, "; char str[10]; strncpy(str, in, 2); printf("output = %s", str); return 0; } My result is nothing, the printf didn't work. But if…
windsound
  • 706
  • 4
  • 9
  • 31
4
votes
6 answers

Copying n chars with strncpy more efficiently in C

I'm wondering if there's a cleaner and more efficient way of doing the following strncpy considering a max amount of chars. I feel like am overdoing it. int main(void) { char *string = "hello world foo!"; int max = 5; char…
Peter Jones
  • 43
  • 1
  • 1
  • 3
3
votes
3 answers

Passing volatile array to strncpy

In my ISR I have a buffer that gets stuffed from the USART so I declared the buffer as volatile: volatile uint8_t RxBuffer1[BUFFER_LENGTH]; Ok, no problem there. I believe that is standard practice. Somewhere in main() I need to copy a portion of…
user1160866
  • 157
  • 2
  • 10
3
votes
2 answers

strncpy overwrites existing character string

I've created a function to convert a number into a roman numeral. I know the logic of the conversion itself is correct, however, each time strncpy is called, it overwrites the previous value of "rom". I even tried calling it back to back and it only…
stan
  • 4,885
  • 5
  • 49
  • 72
3
votes
3 answers

Why does strncpy() produce garbage when the dest is smaller than the src but large enough to fit the wanted substring of src?

I tried to limit the number of n bytes copied to dest (here str1) by using strncpy(). The dest is big enough for the n bytes, but the output produced garbage when dest is smaller than the source (here argv[1]). This looks different, when i make dest…
Coder
  • 197
  • 6
3
votes
6 answers

Do strncpy/memcpy/memmove copy the data byte by byte or in another efficiently way?

As we know, in a multi-bytes word computer such as x86/x86_64, it is more efficiently to copy/move a big bulk of memory word by word (4 or 8 bytes per step), than to do so byte by byte. I'm curious about which way would strncpy/memcpy/memmove do…
Leon
  • 1,489
  • 1
  • 12
  • 31
1
2
3
16 17