-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_strdup.c
69 lines (60 loc) · 1.26 KB
/
ft_strdup.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
* LIBRARY: <string.h>
* ft_strdup(): save a copy of a string (with malloc).
*
* DESCRIPTION:
* ============
* The strdup(): returns a pointer to a new string which is a duplicate of the
* string s.
* Memory for the new string is obtained with malloc().
* It returns NULL if insufficient memory was available.
*/
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
char *ft_strdup(const char *s1)
{
char *s2;
size_t n;
/*
* strlen(s1) + 1 :
* The 1 that i added is for the Null.
* for more clarification, you can visualize the process with
* https://pythontutor.com/c.html#mode=edit
*/
s2 = (char *)malloc(strlen(s1) + 1);
n = 0;
/*
* It returns (NULL) if insufficient memory was available. so it
* basically i'm checking that the memory was created properly:
* (!((char *)malloc(strlen(s1) + 1)))
*/
if (!s2)
{
return (NULL);
}
while (n < strlen(s1))
{
s2[n] = ((char *)s1)[n];
n++;
}
s2[n] = '\0';
return s2;
}
int main()
{
const char *s1;
char *s2;
s1 = "123456789";
s2 = ft_strdup(s1);
printf("%lu\n", strlen(s1));
printf("%s\n", s2);
return EXIT_SUCCESS;
}
/*
* Note:
* =====
* do not forget to replace strlen(s1) with ft_strlen(s1), and include the
* heder for that:
* # include "libft.h"
*/