Scott Pfiffer
Scott Pfiffer

Reputation: 17

strncpy() to get end of string

I am using C Style strings for a project, and I am confusing myself a bit. I am checking strings to see what they are prepended with (zone_, player_, etc) then getting the rest of the string after that.

else if(strncmp(info, "zone_", 5) == 0)
{
    int len = strlen(info);
    char *zoneName = new char[len];
    strncpy(zoneName, &info[5], len-5);

    Msg("Zone Selected: %s\n", zoneName);
    delete zoneName;
}

When I print out the zoneName variable though, it is correct except it is followed by a bunch of gibberish. What am I doing wrong? (I realize that the gibberish is the rest of the char array being empty, but I don't know a better way to do this)

Upvotes: 1

Views: 4871

Answers (4)

icecrime
icecrime

Reputation: 76755

See strncpy description :

No null-character is implicitly appended to the end of destination, so destination will only be null-terminated if the length of the C string in source is less than num.

Upvotes: 3

Greg Hewgill
Greg Hewgill

Reputation: 993105

You have to remember that C-style strings are terminated with a NUL character. You've allocated enough space in zoneName, but you only need len-5 plus one:

char *zoneName = new char[len - 5 + 1];

Then, you can actually use strcpy() to copy the tail of the string:

strcpy(zoneName, &info[5]);

You don't need to specify the length because the source string is NUL terminated.

Upvotes: 1

Martin Kosek
Martin Kosek

Reputation: 398

C-style strings has to be finished with a byte with zero value. You should modify your code like this:

char *zoneName = new char[len-5+1];
strncpy(zoneName, &info[5], len-5);

/* correct string ending */
zoneName[len]=0;

/* Now, it's safe to print */
Msg("Zone Selected: %s\n", zoneName);

Upvotes: 0

sje397
sje397

Reputation: 41822

C strings are zero terminated - so they occupy len bytes (chars to be precise) plus one more with value zero known as the 'zero terminator'. You need to allocate one more character, and either copy one more from the source (since it should be zero terminated) or just set the last char of the destination to 0.

int len = strlen(info);
char *zoneName = new char[len - 5 + 1];
strncpy(zoneName, &info[5], len - 5 + 1);

Upvotes: 0

Related Questions