Skip to content

strlcpy

Marcos edited this page Oct 1, 2024 · 1 revision

La función ft_strlcpy copia una cadena de caracteres desde src a dst, asegurando que la cadena de destino esté siempre terminada en nulo ('\0'). La función devuelve la longitud de la cadena fuente.

Explicación del comando man

STRLCPY(3) (simplified)

NAME
    strlcpy -- size-bounded string copying
SYNOPSIS
    size_t strlcpy(char *dst, const char *src, size_t dstsize);
DESCRIPTION
    The strlcpy() function copy strings with the same input parameters and output result as snprintf(3). It is designed to be safer, more consistent, and less error prone replacement for the easily misused function strncpy(3)
    strlcpy() take the full size of the destination buffer and guarantee NUL-termination if there is room. Note that room for the NUL should be included in dstsize. Also note that strlcpy() only operate on true ''C'' strings. This means that for strlcpy() src must be NUL-terminated.
    strlcpy() copies up to dstsize - 1 characters from the string src to dst, NUL-terminating the result if dstsize is not 0.
    If the src and dst strings overlap, the behavior is undefined.
RETURN VALUES
    The strlcpy() function return the total length of the strings it tried to create. That means the length of src.
    If the return value is >= dstsize, the output string has been truncated.
    It is the caller's responsibility to handle this.

Explicación con mis palabras

La función strlcpy() copia hasta dstsize - 1 caracteres de la cadena src a la cadena dst, garantizando que el resultado esté terminado en nulo ('\0'). La función siempre devuelve la longitud de la cadena fuente src, incluso si ha habido truncamiento (cuando la longitud de la cadena fuente es mayor que el tamaño de destino).

Implementación en C

Aquí te muestro mi implementación de la función ft_strlcpy en mi proyecto de Libft.

Código de ft_strlcpy

#include "libft.h"

size_t	ft_strlcpy(char *dst, const char *src, size_t dstsize)
{
	size_t	length;
	size_t	i;

	// Calculamos la longitud de la cadena fuente
	length = 0;
	i = 0;
	while (src[length])
	{
		length++;
	}

	// Si el tamaño del destino es 0, solo devolvemos la longitud de la fuente
	if (dstsize == 0)
	{
		return (length);
	}

	// Copiamos hasta dstsize - 1 caracteres, asegurando la terminación en '\0'
	while (i < dstsize - 1 && src[i] != '\0')
	{
		dst[i] = src[i];
		i++;
	}

	// Aseguramos la terminación de la cadena destino en '\0'
	dst[i] = '\0';

	// Devolvemos la longitud de la cadena fuente
	return (length);
}

Main para probar ft_strlcpy

El siguiente código es un ejemplo de cómo puedes probar la función ft_strlcpy():

#include <stdio.h>

size_t	ft_strlcpy(char *dst, const char *src, size_t dstsize);

int main(void)
{
	char src[] = "Libft";
	char dst[10];
	size_t length;

	length = ft_strlcpy(dst, src, sizeof(dst));
	printf("Cadena fuente: %s\n", src);
	printf("Cadena destino: %s\n", dst);
	printf("Longitud de la cadena fuente: %zu\n", length); // Debe devolver 5

	return 0;
}

Recomendaciones o ejemplos de uso

  • ¿Por qué usar strlcpy?
    strlcpy es ideal para copiar cadenas de manera segura, ya que previene desbordamientos de buffer al asegurarse de que nunca se sobrepase el tamaño especificado. Además, garantiza que la cadena de destino siempre esté terminada en nulo ('\0').

  • ¿Cuándo usar strlcpy?
    Usa strlcpy cuando quieras copiar una cadena de caracteres a un buffer limitado en tamaño y necesites estar seguro de que no habrá desbordamientos de memoria. Es útil en aplicaciones que requieren seguridad y robustez, como cuando manejas entradas del usuario.

  • Alternativas:
    Si no te preocupa el tamaño del buffer de destino o el riesgo de desbordamiento, puedes usar strcpy. Sin embargo, strcpy no es seguro, ya que no verifica los límites del buffer de destino, lo que podría causar errores o vulnerabilidades.

Clone this wiki locally