Michael Blake
Michael Blake

Reputation: 995

strncpy adding extra characters to my char array

I have a character array of words. Some of them surrounded by *. If one is found, I want it put into my buffer array. I looked at test[i] + 1 in my watch window, and it does what I want. It reads as "example*". I figured if I used strncpy to copy this over with two less characters than the size of it, I would get "example", but instead, I'm getting things like "examples." or "examplers.", which doesn't make any sense to me.

char ** test;
char * buffer;
int elemLen;
if (*test[i] == '*')
{
    elemLen = strlen(test[i]);
    strncpy(buffer, test[i] + 1, elemLen - 2);
}

Upvotes: 4

Views: 3059

Answers (2)

Austinh100
Austinh100

Reputation: 598

You must manually add a null character as strncopy will not do it for you.

i.e.

elemLen = strlen(test[i]);
strncpy(buffer, test[i] + 1, elemLen - 2);
buffer[elemLen - 2] = '\0';

Upvotes: 7

M.M
M.M

Reputation: 141554

The str part of strncpy refers to the fact that it takes a string as input. It doesn't always create a string as output.

My advice would be not to use it, because a lot of people who read your code will be in the same boat as you and not realize that it doesn't create a string as output.

Further, the third parameter to strncpy is supposed to be the destination buffer size. If you are actually trying to specify a number of characters to copy, then you're conflicting with strncpy's purpose because it's supposed to read a null-terminated string as input, not a number of characters.

In fact it is not even clear from your code how much memory buffer is pointing to. If you've already determined buffer is big enough, then strncpy is not the right function because it exists to limit buffer overflows, but there is no danger of overflowing the buffer.

Here are two alternative approaches, where s is the string and you have made sure buffer is big enough:

size_t len = strlen(s);
sprintf(buffer, "%.*s", (int)len - 2, s + 1);

or

size_t len = strlen(s);
memcpy(buffer, s + 1, len - 2);
buffer[len - 2] = '\0';

Note: It would also be a smart move to check len >= 2 before copying the characters; and the sprintf version is easily modifiable (by using snprintf) to also take the output buffer size as a parameter.

Upvotes: 0

Related Questions