We help IT Professionals succeed at work.

C strings strncpy and memcpy

cfans
cfans asked
on
Medium Priority
746 Views
Last Modified: 2012-06-27
I'm having a problem with C strings I can't understand it..

I'm trying to get a section out of a string..

char section[5];

char tempString[32] = "123456ABCDEFGHIJKLMNOPQRSTUVWXYZ";

memcpy(section, tempString + 16, 5);

printf("%s", section);

I get KLMNOÖÿ¿`X@
Comment
Watch Question

Top Expert 2005
Commented:
You copy five characters into section, but section now lacks a NUL terminating byte.  C strings are terminated by byte of 0.  When you call printf(), printf runs off the end of section[] looking for the NUL byte and stops when it eventually finds one somewhere in memory.

Try this:

char section[6];

char tempString[32] = "123456ABCDEFGHIJKLMNOPQRSTUVWXYZ";

memcpy(section, tempString + 16, 5);
section[5] = '\0';

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
x4u
Commented:
You forgot to terminate your string with a 0 byte. Because of this printf treated all memory after the end of your string as part of it until it found a 0 byte.

In C the end of strings needs to be terminated this way. This is already done automatically for literal strings like "abc" which actually consists of 4 bytes: 'a', 'b', 'c', '\0'.

This is your code with correct termination:

char section[6]; // need one byte more

char tempString[32] = "123456ABCDEFGHIJKLMNOPQRSTUVWXYZ";

memcpy(section, tempString + 16, 5);

section[5] = '\0'; // last byte

printf("%s", section);
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.