Last active
August 29, 2015 14:15
-
-
Save alexpreynolds/16cfca7bac5014813a37 to your computer and use it in GitHub Desktop.
Test of string copying with memcpy()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Compile with:
$ gcc -Wall candle_test.c -o candle_test