I'm working on the implementation of strdup()
in C, I'm new to C and I'm trying to build my own library. I'm using the actual strdup()
from string.h
to test mine and I run into a bus error when I test my source against a main program but none when I use the actual strdup()
. Also I can't use any existing functions excluding malloc()
.
Source code:
#include <stdlib.h>
char *ft_strdup(char *src)
{
char *str;
int len;
while (src[len])
len++;
str = (char*)malloc(sizeof(*str) * (len+1));
while (*src)
*str++ = *src++;
*str = '\0';
return (str);
}
Why do I keep getting a bus error?
The strdup() and strndup() functions are used to duplicate a string. strdup() : Syntax : char *strdup(const char *s); This function returns a pointer to a null-terminated byte string, which is a duplicate of the string pointed to by s.
The function strdup() is used to duplicate a string. It returns a pointer to null-terminated byte string.
The strdup() function shall return a pointer to a new string on success. Otherwise, it shall return a null pointer and set errno to indicate the error. Upon successful completion, the strndup() function shall return a pointer to the newly allocated memory containing the duplicated string.
Use g_strdup() instead of strdup().
Try following fix:
len
before increment it.malloc
's return value, and don't use sizeof(char)
, it's defined to be 1 in the standard, per cstd 6.5.3.4p4:
When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1.
str
pointer#include <stdlib.h>
char *ft_strdup(char *src)
{
char *str;
char *p;
int len = 0;
while (src[len])
len++;
str = malloc(len + 1);
p = str;
while (*src)
*p++ = *src++;
*p = '\0';
return str;
}
If you must implement your own strdup
function, at least rely on the rest of string.h for as much as you can. Many of these functions are optimized, and faster than you can write them yourself. For example, strlen
is probably using SSE instructions, while your manual search for the null-terminator byte is not. It's also less code, which is always better. In short, I would suggest this:
#include <stdlib.h>
#include <string.h>
char *ft_strdup(const char *s1)
{
char *str;
size_t size = strlen(s1) + 1;
str = malloc(size);
if (str) {
memcpy(str, s1, size);
}
return str;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With