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
2
votes
5 answers

strncpy copying more than the specified size

I have the following sample code that mimics the code in the application. #include #include #include #include using namespace std; void test(char *s, int size) { //s = ""; int lens…
Arun M
  • 25
  • 2
  • 5
2
votes
1 answer

Copying integer to integer with allocated memory

I have a problem with the code below. ... int anInteger; ... //anInteger gets a value ... int *anotherInteger; label = (int *)malloc(sizeof(int)); strncpy(anotherInteger, anInteger, 40); Essentially what I want to do is to copy the value from an…
Fjodor
  • 529
  • 1
  • 7
  • 19
2
votes
4 answers

How to create my own strcpy function?

I am trying to design a program in which I will create a 3 functions that resemble functions in the c-standard library (strlen,strcmp,strcpy). The first two I have gotten close to finishing, only the last one is the main problem. I am trying to…
Nathan Anderson
  • 21
  • 1
  • 1
  • 3
2
votes
1 answer

strncpy append 1 extra(weird or random)char

I wrote a simple c program that only take the first two characters of one word and take the last three characters of the second word. I use strncpy to only copy the first 2 letter of name1 to name, and concatenate with the last three characters from…
eded
  • 3,778
  • 8
  • 28
  • 42
2
votes
1 answer

SEGMENTATION FAULT in strncpy - load from dictionary

I have this function "load" where I read words from a dictionary and put them in an hashtable of linked lists. When I try to read a line and save it in my new_node->text the compiler returns SEGMENTATION FAULT and I don't know why. The error…
2
votes
4 answers

Using strncpy() to copy const char *

I'm very new to C, I'm getting stuck using the strncpy function.\ Here's an example of what I'm working with: int main() { const char *s = "how"; struct test { char *name; }; struct test *t1 = malloc(sizeof(struct test)); strncpy(t1->name,…
user908015
2
votes
1 answer

strncpy behavior differs from sprintf's

I am using the following code to create a 'Key' to be used to test a hash table (in particular, I am testing the time required to remove items): void remove_keys() { for (int i = 0; i < NUM_ITEMS; i++) { char temp_key[20]; …
goodolddays
  • 2,595
  • 4
  • 34
  • 51
2
votes
5 answers

Garbage being printed when using strcpy

I have a function that will parse some data coming in. My problem is that after using strncpy I get some garbage when I try to print it. I try using malloc to make the char array the exact size. Code: void parse_data(char *unparsed_data) { char…
dead_jake
  • 523
  • 2
  • 12
  • 30
1
vote
5 answers

strncpy char string issue when adding length

I'm having a problem with comparing 2 char strings that are both the same: char string[50]; strncpy(string, "StringToCompare", 49); if( !strcmp("StringToCompare", string) ) //do stuff else //the code runs into here even tho both strings are the…
codrgi
  • 211
  • 1
  • 4
  • 10
1
vote
1 answer

Strncpy() string length output error

I am having a problem with strncpy() copying an extra character at the length I need. I need to copy the 10 most significant bits from one string to another (both in char* format). The size of the larger variable does not intuitively matter, and the…
Jojo Jonas
  • 225
  • 2
  • 4
  • 15
1
vote
0 answers

Why isn't strncpy working to copy a string to a variable of a struct?

I have the following struct in my code: typedef struct { uint64_t pulse; fp_t volume; fp_t factor; // Factor en pulsos / unidad de volumen char *unit_volume; char *unit_time; } totalizer_t; and it is initialized as static with 3…
1
vote
1 answer

Combine multiple boost::asio::const_buffer into a single buffer

My program receives data in the form of std::vector buf_vect. I need to combine the const_buffer in the vector into a single buffer which will then be converted to a std::string for further processing. First…
Steve
  • 77
  • 5
1
vote
1 answer

Implementing a custom input function

I tried 2 different approaches to build a function that accepts string input from user and stores it in a variable. Implementation A char* input(size_t size) { char buffer[size]; char* str = (char*)malloc(sizeof(char) * sizeof(buffer)); …
Zaki
  • 107
  • 9
1
vote
1 answer

C++ custom-written strncpy without padding all characters to null is it safe?

#include using namespace std; struct Packet { int a; char b[17]; int c; }; // char* dest has form char dest[n], src has length <= n and is null-terminated // After the function, dest should satisfy: // - If strlen(src)==n,…
Huy Le
  • 1,439
  • 4
  • 19
1
vote
4 answers

Storing tokens from 1D char array to char** array

I am trying to write a program that will dynamically allocate enough space to store all the words in a 1D char array separated by a space. ex: char *literal = "The quick brown fox"; char **words = { "The", "quick", "brown", "fox" }; The program I…
Kyle C
  • 43
  • 4