Skip to content

Instantly share code, notes, and snippets.

@Pycz
Created September 20, 2013 04:35
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 Pycz/6633342 to your computer and use it in GitHub Desktop.
Save Pycz/6633342 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
/* Functions don't check a 'correctness' of strings
* (except NULL checks) because of a structure of
* strings in C - I mean '\0' termination -
* - it's a question of performance. */
/* Actually, in first variant return values was useful.
* You can use it in some other code, it'll be shown
* below. So I didn't change it.*/
/* Arguments and out-of-memory validation also added */
char* str_cpy(char** dest, const char* src)
/* Copy src string into dest location with memory
* allocation. Intersection in memory is possible.
* Returns *dest */
{
if(!src) /*Can't be NULL, because then nothing to copy*/
return NULL;
size_t len = strlen(src) + 1;
/* Allocate memory if *dest == NULL */
void* new = realloc(*dest, len);
/* If Out-Of-Memory */
if(!new)
return NULL;
return *dest = memmove(new, src, len);
}
char* str_cat(char** dest, const char* src)
/* Concatenate src string to the end of *dest
* with memory allocation.
* Returns *dest */
{
/* NULL - isn't a string, concatenation isn't defined*/
if(!dest || !(*dest) || !src) return NULL;
size_t dest_len = strlen(*dest);
size_t src_len = strlen(src) + 1;
void* new = malloc(dest_len + src_len);
/* If OutOfMemory */
if(!new) return NULL;
memcpy(new, *dest, dest_len);
/* That's interesting moment. Realisation of str_free()
* don't needed in this task, and it's not so simple
* to write 'perfect' realisation of this and
* realisation is platform depended. But I actually
* can use it in my code to clean off unused memory. */
str_free(dest);
return *dest = memcpy(new + dest_len, src, src_len) - dest_len;
}
int main(int argc, char *argv[])
{
char *s = NULL;
char *b = "begin";
char *e = "end";
char *b1 = "high";
char *e1 = "low";
char *copy = NULL;
str_cpy(&s, "Hola Hola");
puts(s);
str_cpy(&s, s+5);
puts(s);
str_cat(&s, " World");
puts(s); /* result: "Hola World!" */
str_cat(&b1, str_cat(&b, e));
puts(b1); /* result: "highbeginend" - for multiconcatenation*/
puts(str_cat(&b1, e1)); /* concatenation and output together*/
puts(str_cat(&e1, str_cpy(&copy, e1))); /* copy and dublicate*/
/* etc... */
str_free(&s);
str_free(&b);
str_free(&e);
str_free(&b1);
str_free(&e1);
str_free(&copy);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment