Skip to content

Instantly share code, notes, and snippets.

@RagedUnicorn
Created December 29, 2018 17:21
Show Gist options
  • Select an option

  • Save RagedUnicorn/3e6fa1ef51472a317a95ea44fac3c627 to your computer and use it in GitHub Desktop.

Select an option

Save RagedUnicorn/3e6fa1ef51472a317a95ea44fac3c627 to your computer and use it in GitHub Desktop.
Safe concatenating of strings in C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void safeConcatenate(char *buffer, int size, char *string1, char *string2);
int main(int argc, char *argv[]) {
char buffer[1024] = {0};
char *string1 = "foo";
char *string2 = "bar";
safeConcatenate(buffer, 1024, string1, string2);
printf("Concatenated string: %s\n", buffer);
}
void safeConcatenate(char *buffer, int size, char *string1, char *string2) {
if (strlen(string1) + strlen(string2) > size) {
printf("Bufferoverflow!");
exit(1);
} else {
strcat(buffer, string1);
strcat(buffer, string2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment