What happens if strncpy copies random data into a buffer?

  • A+
Category:Languages

Suppose you have a char buffer that you want to copy an std::string into. Are there consequences of copying extra data into the buffer, outside of the strings scope, even though the buffer has adequate size?

Example

std::string my_string = "hello"; char my_buffer[128]; memset(my_buffer, 0, 128);  strncpy(my_buffer, my_string.c_str(), 128); 

So "hello" gets copied into my_buffer, but so will 123 other bytes of data that comes after my_string. Are there any consequences of this? Is it harmful for the buffer to hold this other data?

 


but so will 123 other bytes of data that comes after my_string

This assumption is incorrect: strncpy pays attention to null termination of the source string, never reading past null terminator. The remaining data will be set to '/0' characters:

destination is padded with zeros until a total of num characters have been written to it. [reference]

This is in contrast to memcpy, which requires both the source and the destination to be of sufficient size in order to avoid undefined behavior.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: