Skip to content

Instantly share code, notes, and snippets.

@olafurjohannsson
Last active August 3, 2016 22:32
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 olafurjohannsson/735ad09ca9aedafc3b3e3b74c3f496ed to your computer and use it in GitHub Desktop.
Save olafurjohannsson/735ad09ca9aedafc3b3e3b74c3f496ed to your computer and use it in GitHub Desktop.
C stdlib functions
#include "stdlib.h"
/*
* string_length:
* Returns the length of the pointer *s
* Same as strlen in <stdlib>
*/
unsigned long string_length(const char *s) {
int c = 0;
// dereference the pointer until EOF and raise the counter variable
while (*s++) c++;
return c;
}
/*
* string_copy:
* Copies the string *src to *dst
* Same as strcpy in <stdlib>
*/
void string_copy(const char *src, char *dst) {
while ((*dst++ = *src++) != '\0')
;
}
/*
* string_duplicate:
* Returns the duplicate of the string *s
* Same as strdup in <stdlib>
*/
char *string_duplicate(char *s) {
// start by allocating enough memory for the string + '\0'
char *p = (char*)malloc(string_length(s) + 1);
// if success we copy the string
if (p != NULL)
string_copy(p, s);
return p;
}
#ifndef STDLIB_H
#define STDLIB_H
extern unsigned long string_length(const char *s);
extern void string_copy(const char *src, char *dst);
extern char *string_duplicate(char *s);
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment