Search code examples
carrayscharsegmentation-faultxor

C segmentation fault xor char array


I want to xor a certain value on all of my chars in a char array. I have some code that works all fine except for the xor line:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void obfuscate(FILE *file, char *input, char *variableName)
{
    int i;
    int size = (int)strlen(input);
    char a = 65;
    fprintf(file, "%s: %s -> ", variableName, input);

    for(i = 0; i < size; i++)
    {
        input[i] = (char)(input[i] ^ a);//I am causing a segmentation fault
        fprintf(file, "0x%x, ", input[i]);
    }
    return;
}

int main()
{
    char *a = "MyString";
    FILE *file = fopen("out.txt", "w");
    obfuscate(file, a, "a");
    fclose(file);
}

I use the normal gcc compiler with gcc in.c -o out.o on a linux machine.

If I comment the line with the xor operation it works just fine. Any help is highly appreciated, my own research did not result in a solution.


Solution

  • Try below solution with dynamic memory.
    In char *a = "MyString"; char *in = malloc(sizeof(a));
    a is pointing to code section we can't alter it. & in is pointing to heap section, so we can modify it any no.of times.

    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    
    void obfuscate(FILE *file, char *input, char *variableName)
    {
        int i;
        int size = (int)strlen(input);
        char a = 65;
        fprintf(file, "%s: %s -> ", variableName, input);
    
        for(i = 0; i < size; i++)
        {
            input[i] = (char)(input[i] ^ a);//I am causing a segmentation fault
            fprintf(file, "0x%x, ", input[i]);
        }
        return;
    }
    
    int main()
    {
        char *a = "MyString";
        char *in = malloc(sizeof(a));
        strcpy(in, a);
        FILE *file = fopen("out.txt", "w");
        obfuscate(file, in, "a");
        fclose(file);
        free(in);
    }