Skip to content

Instantly share code, notes, and snippets.

@alexpreynolds
Last active August 29, 2015 14:15
Show Gist options
  • Save alexpreynolds/16cfca7bac5014813a37 to your computer and use it in GitHub Desktop.
Save alexpreynolds/16cfca7bac5014813a37 to your computer and use it in GitHub Desktop.
Test of string copying with memcpy()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LETTERS 5
int main(int argc, char *argv[])
{
const char *source = "candle";
char *destination = NULL;
destination = malloc(MAX_LETTERS + 1);
if (!destination) {
fprintf(stderr, "Error: Could not allocate space for destination string\n");
return EXIT_FAILURE;
}
if (strlen(source) > MAX_LETTERS) {
memcpy(destination, source, MAX_LETTERS);
destination[MAX_LETTERS] = '\0'; /* add null terminator */
}
else {
memcpy(destination, source, strlen(source) + 1); /* copy over null from source */
}
fprintf(stdout, "destination: [%s]\n", destination);
free(destination);
return EXIT_SUCCESS;
}
@alexpreynolds
Copy link
Author

Compile with: $ gcc -Wall candle_test.c -o candle_test

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment