FreeNOS
strndup.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2009 Niek Linnenbank
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program. If not, see <http://www.gnu.org/licenses/>.
16  */
17 
18 #include "stdlib.h"
19 #include "string.h"
20 #include "sys/types.h"
21 
22 char * strndup(const char *s, size_t size)
23 {
24  size_t bytes;
25  char *buff;
26 
27  // Fetch input string length
28  bytes = strlen(s);
29 
30  // Calculate bytes to allocate
31  if (bytes > size)
32  {
33  bytes = size;
34  }
35 
36  // Allocate buffer
37  if ((buff = (char *) malloc(bytes + 1)) == NULL)
38  {
39  return (char *) NULL;
40  }
41 
42  // Copy input into new buffer
43  memcpy(buff, s, bytes + 1);
44 
45  // Null terminate
46  buff[bytes] = 0;
47 
48  // Done
49  return buff;
50 }
strlen
size_t strlen(const char *str)
Calculate the length of a string.
Definition: strlen.cpp:21
types.h
string.h
strndup
char * strndup(const char *s, size_t size)
Duplicate a specific number of bytes from a string.
Definition: strndup.cpp:22
malloc
C void * malloc(size_t size)
A memory allocator.
Definition: malloc.cpp:22
NULL
#define NULL
NULL means zero.
Definition: Macros.h:39
stdlib.h
memcpy
void * memcpy(void *dest, const void *src, size_t count)
Copy memory from one place to another.
Definition: memcpy.cpp:20