SIGSEGV segmentation fault by allocating 8MB

Hey all,

I was debugging my XOR algorithm and I found my program crashing when I tried a bit larger files.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
void encryptWidget::XOR()
{
    std::string path = filePathEdit->text().toStdString();
    std::ifstream file(path.c_str(), std::ifstream::binary);

    struct stat results;
    stat(path.c_str(), &results);

    char buffer[results.st_size]; // <--- SEGMENTATION FAULT
    file.read(buffer, results.st_size);

    //start encryption
    std::string key = keyEdit->text().toStdString();
    int i = 0;
    for(long long j = 0; j < results.st_size; j++)
    {
        i++;
        if(i > key.size())
            i = 0;
        buffer[j] = key[i] ^ buffer[j];
    }
    file.close();

    std::ofstream outputFile;
    outputFile.open(path.c_str(), std::ofstream::binary);
    outputFile.write(buffer, results.st_size);

}


any ideas?
ISO C++ forbids variable length array.
Huh?
It does work with smaller files?
text files, mp3 files and stuff...
You are allocating the array on the stack so it is probably a stack overflow. Try allocate the buffer on the free store instead.
Last edited on
How do I do that?

EDIT: Nevermind I got it! Thanks Peter87, that's the second question of me you've solved in less than a week :D
Last edited on
Peter87, that's the second question of me you've solved in less than a week :D

I have no life :(
It does work with smaller files?

Because your compiler allows non-standard behaviour. By all means take advantage of that, but it's only right that you should be aware of it. It's especially bad news if you want your code to be portable.
Hmmm I see :)
And Peter, you have no life because you solved 2 questions? haha
Topic archived. No new replies allowed.