Skip to content

Instantly share code, notes, and snippets.

@dheater
Last active March 17, 2019 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dheater/8760a9fda957c2720a0b18cab0735649 to your computer and use it in GitHub Desktop.
Save dheater/8760a9fda957c2720a0b18cab0735649 to your computer and use it in GitHub Desktop.
Safer version of strcpy/strncpy/strlcpy
#include "strlncpy.h"
size_t strlncpy(char *dst, const char *src, size_t dbytes, size_t sbytes)
{
char *d = dst;
const char *s = src;
size_t n = (dbytes > sbytes) ? sbytes : dbytes;
/* Copy as many bytes as will fit */
while(n-- > 0) {
if('\0' == (*d++ = *s++))
break;
}
/* Not enough room in dst */
if(0 == n && dbytes != 0)
*d = '\0'; /* NUL-terminate dst */
return d - dst - 1; /* count does not include NUL */
}
/*
* Copyright (c) 2019 Daniel L. Heater
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE
* LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY
* DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
* ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef __STRLNCPY_H__
#define __STRLNCPY_H__
#include <stddef.h>
/**
* Safer version of str[nl]cpy()
* Always NUL terminates (unless dbytes== 0).
* @param dst Destination string to copy to.
* @param src Source string to copy from.
* @param dbytes Length of the destination buffer.
* @param sbytes Length of the sourcebuffer.
* @retrun The number of bytes copied.
*/
size_t strlncpy(char *dst, const char *src, size_t dbytes, size_t sbytes);
#endif /* __STRLNCPY_H__ */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment