Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - read string from buffer of certain size

I have a char buf[x], int s and void* data.

I want to write a string of size s into data from buf.

How can I accomplish it?

Thanks in advance.

like image 632
Rok Povsic Avatar asked Jul 18 '10 15:07

Rok Povsic


1 Answers

Assuming that

  • by “string” you mean a null-terminated string as is normally meant in C;
  • you haven't yet allocated memory in data;
  • you already know that s <= x

First you need to allocate memory in data. Don't forget the room for the 0 byte at the end of the string.

data = malloc(s+1);
if (data == NULL) {
    ... /*out-of-memory handler*/
}

Assuming malloc succeeds, you can now copy the bytes.

EDIT:

The best function for the job, as pointed out by caf, is strncat. (It's fully portable, being part of C89.) It appends to the destination string, so arrange for the destination to be an empty string beforehand:

*(char*)data = 0;
strncat(data, buf, s);

Other inferior possibilities, kept here to serve as examples of related functions:

  • If you have strlcpy (which is not standard C but is common on modern Unix systems; there are public domain implementations floating around):

    strlcpy(data, buf, s+1);
    
  • If you know that there are at least s characters in the source string, you can use memcpy:

    memcpy(data, buf, s);
    

    ((char*)data)[s+1] = 0;

  • Otherwise you can compute the length of the source string first:

    size_t bytes_to_copy = strlen(buf);
    if (bytes_to_copy > s) bytes_to_copy = s;
    memcpy(data, buf, bytes_to_copy);
    ((char*)data)[s+1] = 0;
    
  • Or you can use strncpy, though it's inefficient if the actual length of the source string is much smaller than s:

    strncpy(data, buf, s);
    ((char*)data)[s+1] = 0;
    
like image 133
Gilles 'SO- stop being evil' Avatar answered Oct 26 '22 00:10

Gilles 'SO- stop being evil'