Assuming that
- "string" means a zero-terminated string, as is usually implied in C;
- You have not allocated a memory in
data; - You already know that s <= x
First you need to allocate memory in data. Do not forget the byte room 0at the end of the line.
data = malloc(s+1);
if (data == NULL) {
...
}
, malloc , .
, , strncat. ( , C89.) , :
*(char*)data = 0;
strncat(data, buf, s);
, , :
strlcpy ( C, Unix-, public domain):
strlcpy(data, buf, s+1);
, s , memcpy:
memcpy(data, buf, s);
((char *)) [s + 1] = 0;
:
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;
strncpy, , s:
strncpy(data, buf, s);
((char*)data)[s+1] = 0;