Search code examples
csegmentation-faultfopen

Segfault when opening filename provided by argv even though it exists in argv


I made a little repeating XOR encryptor. You can xor a string of your choice with a key of your choice, and it will optionally output it to a file.

Whenever running the program with a single-word (no spaces) string and key, there are no problems. Whenever there are spaces in either string or key however, the program segfaults on the fopen line (even though argv[3] is the actual filename, I checked it with a print statement).

Why does it do that?

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

int main(int argc, char const *argv[]){
    int file=0;

    switch(argc){
        case 3:
            break;
        case 4:
            file = 1;
            break;
        default:
            printf("Repeating XOR encryption. Usage:\n./xor \"Your string\" \"Your key\" \"Output filename\" (optional last parameter)");
            return 1;
    }

    const char* string = argv[1];
    const char* key = argv[2];

    int keylen = strlen(key);
    int stringlen = strlen(string);

    unsigned char buffer[keylen];

    unsigned char stringbyte;
    unsigned char keybyte;
    unsigned char newbyte;

    for(int i=0; i<stringlen; i++){
        stringbyte = string[i];
        keybyte = key[i%keylen];
        newbyte = stringbyte ^ keybyte;
        buffer[i] = newbyte;
        printf("%04d: %c^%c=%02hhx\n", i, stringbyte, keybyte, newbyte);
    }

    if(file){
        FILE *fptr;
        fptr = fopen(argv[3],"wb");
        fwrite(buffer, 1, stringlen, fptr);
        fclose(fptr);
    }else{
        for(int i=0; i<stringlen; ++i){
            printf("%c", buffer[i] );
        }
    }

    printf("\n");

    return 0;
}

input:

./xor "multiple words in a sentence" "the Key" "file"

output:

0000: m^t=19
0001: u^h=1d
0002: l^e=09
0003: t^ =54
0004: i^K=22
0005: p^e=15
0006: l^y=15
0007: e^t=11
0008:  ^h=48
0009: w^e=12
0010: o^ =4f
0011: r^K=39
0012: d^e=01
0013: s^y=0a
0014:  ^t=54
0015: i^h=01
0016: n^e=0b
0017:  ^ =00
0018: a^K=2a
0019:  ^e=45
0020: s^y=0a
0021: e^t=11
0022: n^h=06
0023: t^e=11
0024: e^ =45
0025: n^K=25
0026: c^e=06
0027: e^y=1c
Segmentation fault (core dumped)

Solution

  • I don't know if this is the answer, but you are looping against stringlen but filling out buffer[i].... buffer is size of keylen, so if stringlen is > keylen length you will get a fault.