Skip to content

Instantly share code, notes, and snippets.

@theteachr
Last active January 28, 2023 11:54
Show Gist options
  • Save theteachr/9fdbdf52202b828c705fb32084d8ad76 to your computer and use it in GitHub Desktop.
Save theteachr/9fdbdf52202b828c705fb32084d8ad76 to your computer and use it in GitHub Desktop.
Destructive XOR
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_CHARS 64
void swap(char* a, char* b) {
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
void rev(char* text, size_t size) {
for (
size_t left = 0, right = size - 1;
left <= right;
left++, right--
) {
swap(text + left, text + right);
}
}
int main(int argc, char* argv[]) {
if (argc < 2) {
fprintf(stderr, "No input param given :o\n");
exit(EXIT_FAILURE);
}
char text[MAX_CHARS];
strncpy(text, argv[1], MAX_CHARS);
rev(text, strlen(text));
printf("Given: %s\n", argv[1]);
printf("Revved: %s\n", text);
}
@ForgotMyCode
Copy link

ForgotMyCode commented Jan 28, 2023

At function rev line 15:
value of variable right will underflow when size is 0.

At functionmain line 32:
result of strlen call may be undefined since the '\0' character maybe was not copied by strncpy.

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