Garlic bread
Garlic bread

Reputation: 1

Segmentation Fault (core dumped) with sprinft format char array index

Need to format a char array but by every index in a for loop but this ends in a Segmentation Fault (core dumped)

#include <iostream>
#include "stdint.h"
#include <cstring> 
 
uint32_t Key = 0xbeefbabe;
 
char message[128];
char encrypted[128];
 
void offuscation () 
{   
 
    int len = strlen(message);
 
    uint8_t k1 = Key & 0xff,
            k2 = (Key >> 8) & 0xff,
            k3 = (Key >> 16) & 0xff,
            k4 = (Key >> 24) & 0xff;
 
    for( int i = 0; i < len; i ++ ) 
    {
 
        message[i] ^= k1;
        message[i] ^= k2;
        message[i] ^= k3;
        message[i] ^= k4;
 
        sprintf((char *)encrypted[i], "\\x%02X", message[i]);
 
 
 
    }
 
}
 
int main () 
{
 
    printf("\n");
 
    strcpy(message, "Help me Please");
 
    offuscation ();
 
    printf("\n\n");
 
    std::cout << encrypted << "\n";
 
}

I need this --> printf("\x%02X", message[i]);

but every index of this array going to be the other

Upvotes: 0

Views: 31

Answers (1)

molbdnilo
molbdnilo

Reputation: 66371

encrypted[i] is a single char - you can't cast it to a pointer and get something useful.
Also, if you encode each char as four characters, you're going to need more space.

Something like this:

char message[128];
char encrypted[4 * 128];
 
void offuscation() 
{   
    int len = strlen(message);
    uint8_t k1 = Key & 0xff,
            k2 = (Key >> 8) & 0xff,
            k3 = (Key >> 16) & 0xff,
            k4 = (Key >> 24) & 0xff;
    uint8_t mask = k1 ^ k2 ^ k3 ^ k4;

    char* output = encrypted;
    for( int i = 0; i < len; i ++ ) 
    {
        output += sprintf(output, "\\x%02X", message[i] ^ mask);
    }
}

Upvotes: 0

Related Questions