Created
December 29, 2018 17:21
-
-
Save RagedUnicorn/3e6fa1ef51472a317a95ea44fac3c627 to your computer and use it in GitHub Desktop.
Safe concatenating of strings in C
This file contains hidden or 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 <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