Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementation of strdup() in C programming

Tags:

c

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?

like image 704
adot Avatar asked May 10 '16 08:05

adot


People also ask

What does strdup () do in C?

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.

What is the point of strdup?

The function strdup() is used to duplicate a string. It returns a pointer to null-terminated byte string.

What does strdup return?

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.

What can I use instead of strdup?

Use g_strdup() instead of strdup().


2 Answers

Try following fix:

  1. Initialize len before increment it.
  2. Don't cast 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.

  3. Use a pointer to save the original 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;
}
like image 110
fluter Avatar answered Sep 28 '22 02:09

fluter


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;
}
like image 38
Enno Avatar answered Sep 28 '22 02:09

Enno