[42seoul] libft (chapter 1)

ppparkta·2022년 7월 9일
0

42Seoul

목록 보기
1/10

chapter 1

헤더파일 작성

  • vim사용시 ./₩t로 현재 탭이 쓰인 곳 확인하기
  • include는 헤더파일에 한해 띄어쓰기로 작성해야 함.
  • 사진 확인하며 norm 규정 지키기

mem function

메모리 함수에서 문자열을 다룰 때

memset

void *ft_memset(void *s, int c, size_t n)

  • s라는 보이드 포인터를 n개만큼 c로 초기화하는 함수

DESCRIPTION
The memset() function writes len bytes of value c (converted to an unsigned char) to the string b.

RETURN VALUES
The memset() function returns its first argument.

#include	"libft.h"

void	*ft_memset(void *s, int c, size_t n)
{
	unsigned char	*sc;
	size_t			i;

	i = n;
	sc = (unsigned char *)s;
	while (i > 0)
	{
		*sc++ = (unsigned char)c;
		i--;
	}
	return (s);
}
Footer

bzero

void ft_bzero(void *s, size_t n)

  • s라는 보이드 포인터를 n개만큼 0으로 초기화하는 함수

DESCRIPTION
The bzero() function writes n zeroed bytes to the string s. If n is zero, bzero() does nothing.

void	ft_bzero(void *s, size_t n)
{
	unsigned char	*sc;
	size_t			i;

	i = n;
	sc = (unsigned char *)s;
	while (i > 0)
	{
		*sc++ = 0;
		i--;
	}
}
Footer

memcpy

void *ft_memcpy(void *dest, const void *src, size_t n)

  • src의 값을 dst에 n사이즈만큼 복사하는 메모리함수
  • src와 dst의 주소가 겹칠 때 원하는 값이 나올수도 있고 안 나올수도 있음

DESCRIPTION
The memcpy() function copies n bytes from memory area src to memory area dst. If dst and src overlap,
behavior is undefined. Applications in which dst and src might overlap should use memmove(3) instead.

RETURN VALUES
The memcpy() function returns the original value of dst.

void	*ft_memcpy(void *dest, const void *src, size_t n)
{
	unsigned char	*pointer;
	size_t			i;

	if (dest == 0 && src == 0)
		return (dest);
	pointer = (unsigned char *)dest;
	i = 0;
	while (i < n)
	{
		*pointer++ = *((unsigned char *)src++);
		i++;
	}
	return (dest);
}

memmove

void *ft_memmove(void *dest, const void *src, size_t n)

  • src의 값을 dst에 n사이즈만큼 복사하는 메모리 함수
  • memcpy와의 차이점은 dst > src라면 값을 뒤에서부터 복사하여 겹치는 공간에 원하는 값이 복사되지 않는 경우를 방지함

DESCRIPTION
The memmove() function copies len bytes from string src to string dst. The two strings may overlap; the
copy is always done in a non-destructive manner.

RETURN VALUES
The memmove() function returns the original value of dst.

void	*ft_memmove(void *dest, const void *src, size_t n)
{
	char			*cdest;
	const char		*csrc;
	size_t			i;

	cdest = dest;
	csrc = src;
	i = 0;
	if (cdest == 0 && csrc == 0)
		return (dest);
	if (cdest >= (char *)csrc)
	{
		cdest += n - 1;
		csrc += n - 1;
		while (i < n)
		{
			*cdest-- = *((char *)csrc--);
			i++;
		}
	}
	else
	{
		while (i < n)
		{
			*cdest++ = *((char *)csrc++);
			i++;
		}
	}
	return (dest);
}

memchr

  • void 포인터 s에서 n까지의 범위 내에 있는 c를 찾아서 그 주소를 반환하는 메모리 함수

DESCRIPTION
The memchr() function locates the first occurrence of c (converted to an unsigned char) in string s.

RETURN VALUES
The memchr() function returns a pointer to the byte located, or NULL if no such byte exists within n bytes.

void	*ft_memchr(const void *s, int c, size_t n)
{
	size_t	i;

	i = 0;
	while (i < n)
	{
		if (((unsigned char *)s)[i] == (unsigned char)c)
			return ((void *)s + i);
		i++;
	}
	return (0);
}

memcmp

  • 특정 메모리에서 원하는 크기만큼 비교하여 결과값을 얻어내는 함수
  • strcmp는 문자열 자체를 비교하지만 이것은 비교할 수 있는 크기를 지정하므로 더 디테일하게 비교할 수 있다는 장점이 있음

DESCRIPTION
The memcmp() function compares byte string s1 against byte string s2. Both strings are assumed to be n
bytes long.

RETURN VALUES
The memcmp() function returns zero if the two strings are identical, otherwise returns the difference
between the first two differing bytes (treated as unsigned char values, so that \200' is greater than \0',
for example). Zero-length strings are always identical. This behavior is not required by C and portable
code should only depend on the sign of the returned value.

int	ft_memcmp(const void *s1, const void *s2, size_t n)
{
	size_t			i;
	unsigned char	*s1len;
	unsigned char	*s2len;

	s1len = (unsigned char *)s1;
	s2len = (unsigned char *)s2;
	i = 0;
	while (i < n)
	{
		if (s1len[i] != s2len[i])
			return (s1len[i] - s2len[i]);
		i++;
	}
	return (0);
}

string function

strlcpy

  • 문자열 src에서 dst로 최대 dstsize - 1을 복사하고 dstsize가 0이 아닌 경우 0을 리턴하는 함수
size_t	ft_strlcpy(char *dst, const char *src, size_t size)
{
	size_t	i;
	size_t	length;

	length = 0;
	i = 0;
	while (src[length])
		length++;
	while (i < length && i + 1 < size)
	{
		dst[i] = src[i];
		i++;
	}
	if (size > 0)
		dst[i] = '\0';
	return (length);
}

strlcat

  • 문자열 src를 dst의 끝에 추가하는 함수
  • 최대 dstize - strlen(dst) - 1 을 추가함
size_t	ft_strlcat(char *dest, char *src, unsigned int size)
{
	size_t	i;
	size_t	d;
	size_t	s;

	d = ft_strlen(dest);
	s = ft_strlen(src);
	if (size <= d)
		return (s + size);
	i = 0;
	while (i < size - 1 - d && src[i])
	{
		dest[d + i] = src[i];
		i++;
	}
	dest[d + i] = 0;
	return (d + s);
}

strncmp

  • 두개의 문자열을 비교하여 문자열이 완전히 같으면 0을 반환하고 다르면 음/양수를 반환하는 함수.
  • n이므로 n까지 비교함

DESCRIPTION
The strcmp() and strncmp() functions lexicographically compare the null-terminated strings s1 and s2.
The strncmp() function compares not more than n characters. Because strncmp() is designed for comparing strings rather than binary data, characters that appear after a \0 character are not compared.

RETURN VALUES
The strcmp() and strncmp() functions return an integer greater than, equal to, or less than 0, according as the
string s1 is greater than, equal to, or less than the string s2. The comparison is done using unsigned characters,
so that \200 is greater than \0.

int	ft_strncmp(const char *s1, const char *s2, size_t n)
{
	unsigned char	*new1;
	unsigned char	*new2;
	size_t			i;

	i = 0;
	new1 = (unsigned char *)s1;
	new2 = (unsigned char *)s2;
	while (n--)
	{
		if (new1[i] != new2[i] || new1[i] == 0 || new2[i] == 0)
			return (new1[i] - new2[i]);
		i++;
	}
	return (0);
}

strchr

  • s문자열 내에서 c를 찾았을 때 그 시작주소를 리턴하는 함수
  • 만약 c를 찾지 못했다면 null포인터를 리턴함
  • \0 도 문자열의 일부로 간주되므로 따로 처리해야 함

DESCRIPTION
The strchr() function locates the first occurrence of c (converted to a char) in the string pointed to by s.
The terminating null character is considered to be part of the string; therefore if c is '\0'', the functions
locate the terminating \0'. The strrchr() function is identical to strchr(), except it locates the last occurrence of c.

RETURN VALUES
The functions strchr() and strrchr() return a pointer to the located character, or NULL if the character does not appear in the string.

char	*ft_strchr(const char *s, int c)
{
	int	i;

	i = 0;
	if (s == 0)
		return (0);
	while (s[i])
	{
		if (s[i] == (char)c)
			return ((char *)&s[i]);
		i++;
	}
	if ((char)c == 0)
		return ((char *)&s[i]);
	return (0);
}

strrchr

  • s문자열에서 c를 찾기 위해 뒤에서부터 탐색하는 함수
  • reverse라고 생각
char	*ft_strrchr(const char *s, int c)
{
	int	i;

	if (s == 0)
		return (0);
	i = ft_strlen(s);
	while (i >= 0)
	{
		if (s[i] == (char)c)
			return ((char *)&s[i]);
		i--;
	}
	return (0);
}

strnstr

  • haystack의 시작지점부터 len까지의 범위 중에서 문자열 needle을 찾아내는 함수
  • needle이 '\0'일 때 haystack을 반환함

DESCRIPTION
The strnstr() function locates the first occurrence of the null-terminated string needle in the
string haystack, where not more than len characters are searched. Characters that appear after a
\0' character are not searched. Since the strnstr() function is a FreeBSD specific API, it should
only be used when portability is not a concern.

RETURN VALUES
If needle is an empty string, haystack is returned; if needle occurs nowhere in haystack, NULL is
returned; otherwise a pointer to the first character of the first occurrence of needle is returned.

char	*ft_strnstr(const char *haystack, const char *needle, size_t len)
{
	size_t	i;
	size_t	j;

	if (*needle == 0)
		return ((char *)haystack);
	i = 0;
	while (i < len && haystack[i])
	{
		j = 0;
		while (i + j < len && haystack[i + j] == needle[j])
		{
			j++;
			if (needle[j] == 0)
				return ((char *)&haystack[i]);
		}
		i++;
	}
	return (0);
}

atoi

  • 문자열로 들어온 숫자를 인티저형으로 형변환하는 함수
  • 부호가 2개 이상인 경우 0으로 처리함
  • 숫자와 숫자를 제외한 문자열이 나오면 처음 나온 숫자만 처리함

atoi함수가 strtol에 의해 작동하는데 strtol의 반환형은 long임. 실제 atoi의 오버/언더플로우 처리결과는 strtol처리과정에서 나오는 부산물임. atoi자체에서 잡아준 것이 아님. 실제 atoi에서 오버플로우가 나면 -1을 반환하고 언더플로우가 나면 0을 리턴함. 다만 우리는 man을 참고해 만드는 것이고 실제 atoi의 동작은 내부에서 strtol함수를 통해 리턴값을 캐스팅해서 받아오는 것임. 따라서 이를 구현하기는 어렵다고 판단하여 오버플로우를 처리하지 않는 아토이를 구현하였음. (단순이 0, -1로 구현하는 것은 무의미)

	printf("return(MIN) : %d\n", atoi("-2147483648"));	 // -2147483648
	printf("return(MAX) : %d\n", atoi("2147483647"));	// 2147483647
	printf("return(MIN-1) : %d\n", INT_MAX);	// 2147483647
	printf("return(MIN-1) : %d\n", atoi("-2147483649")); // 2147483647
	printf("return(MAX+1) : %d\n", INT_MIN); // -2147483648
	printf("return(MAX+1) : %d\n", atoi("2147483648"));	// -2147483648
	printf("return(123aa) : %d\n", atoi("123aa"));	 // 123
	printf("return(123 123) : %d\n", atoi("123 123"));	 // 123
    printf("return(--123) : %d\n", atoi("--123"));	 // 0
    printf("return(-+-123) : %d\n", atoi("-+-123"));	 // 0
    printf("return(++123) : %d\n", atoi("++123"));	 // 0
    printf("return(+-123) : %d\n", atoi("+-123"));	 // 0
    printf("return(-+123) : %d\n", atoi("-+123"));	 // 0

DESCRIPTION
The atoi() function converts the initial portion of the string pointed to by str to int representation.
It is equivalent to:

(int)strtol(str, (char **)NULL, 10);

While the atoi() function uses the current locale, the atoi_l() function may be passed a locale directly.
See xlocale(3) for more information.

int	ft_atoi(const char *str)
{
	size_t			i;
	long long		sym;
	long long		ans;

	i = 0;
	sym = 1;
	ans = 0;
	while ((str[i] >= 9 && str[i] <= 13) || str[i] == 32)
		i++;
	if (str[i] == '-' || str[i] == '+')
	{
		if (str[i] == '-')
			sym *= -1;
		i++;
	}
	if (str[i] >= '0' && str[i] <= '9')
	{
		while (str[i] >= '0' && str[i] <= '9')
		{
			ans = (ans * 10) + (str[i] - '0');
			i++;
		}
		return ((int)(sym * ans));
	}
	return (0);
}

malloc function

calloc

  • size크기의 자료를 count개 저장할 수 있는 공간을 할당해 0으로 초기화한 뒤에 반환하는 함수
  • 널가드 주의
  • 만약 size_t 범위를 초과한 값이 들어오더라도 따로 처리를 하지 않음

DESCRIPTION
The calloc() function contiguously allocates enough space for count objects that are size bytes of memory each and returns a pointer to the allocated memory. The allocated memory is filled with bytes of value zero.

RETURN VALUES
If successful, calloc(), malloc(), realloc(), reallocf(), valloc(), and aligned_alloc() functions return a pointer to allocated memory. If there is an error, they return a NULL pointer and set errno to ENOMEM.

void	*ft_calloc(size_t count, size_t size)
{
	void	*ans;

	ans = malloc(size * count);
	if (ans == 0)
		return (0);
	ft_bzero(ans, (size * count));
	return (ans);
}

strdup

  • s1의 문자열 크기만큼 할당받은 뒤에 s1의 값을 복사하는 함수
  • 널가드 주의

DESCRIPTION
The strdup() function allocates sufficient memory for a copy of the string s1, does the copy, and returns a pointer to it. The pointer may subsequently be used as an argument to the function free(3).
If insufficient memory is available, NULL is returned and errno is set to ENOMEM.

char	*ft_strdup(const char *s1)
{
	size_t	len;
	size_t	i;
	char	*ans;

	len = ft_strlen(s1);
	ans = (char *)(malloc)(sizeof(char) * (len + 1));
	if (ans == 0)
		return (0);
	i = 0;
	while (s1[i])
	{
		ans[i] = s1[i];
		i++;
	}
	ans[i] = 0;
	return (ans);
}
profile
겉촉속촉

0개의 댓글

관련 채용 정보