0
using namespace std;

void *gen_random(void *data, const int len) {
    for (int i = 0; i < len; ++i) {
        *((unsigned char *)data + i) = rand() % UCHAR_MAX;
    }
    return data;
}

void idx_sort_swap(unsigned long long &small, unsigned long long &big){
    unsigned long long tmp;
    if(small > big) {
        tmp = small;
        small = big;
        big = tmp;
    }
}

char *random_manipulate(char *const source, const unsigned long long size,
    unsigned long long &after_size, const unsigned long long max_rand_size){
    stringstream ss;
    char *data_tmp;
    unsigned long long idx_tmp0, idx_tmp1, size_tmp;

    after_size = 0;
    switch(rand() % 2){
        case 0:
        /* WRITE */
        idx_tmp0 = rand() % size;
        size_tmp = rand() % max_rand_size;

        ss.write(source, idx_tmp0);
        after_size += idx_tmp0;

        data_tmp = new char[size_tmp];
        gen_random(data_tmp, size_tmp);
        ss.write(data_tmp, size_tmp);
        delete data_tmp;
        after_size += size_tmp;

        if(size > after_size) {
            ss.write(source + after_size, size - after_size);
            after_size = size;
        }
        break;

        case 1:
        /* DELETE */
        idx_tmp0 = rand() % size;
        size_tmp = rand() % max_rand_size;

        ss.write(source, idx_tmp0);
        after_size += idx_tmp0;

        if(size - (idx_tmp1 = idx_tmp0 + size_tmp) > 0){
            ss.write(source + idx_tmp1, size - idx_tmp1);
            after_size += size - idx_tmp1;
        }
    }

    char *dest;
    dest = new char[after_size];
    ss.read(dest, after_size);
    return dest;
}

random_manipulate() function returns C-style string which randomly manipulates the char *const source as source.

random_manipulate() always evokes segmentation faults when called 2nd time and calling ss.write(source, idx_tmp0); in any of two switch case.

I don't know why since the logic itself seems nothing wrong.

  • 1
    Is `source` a valid pointer? When and how do you call this `random_manipulate` function? Can you please try to create a [Minimal, **Complete**, and Verifiable Example](http://stackoverflow.com/help/mcve) to show us? – Some programmer dude Nov 19 '17 at 16:19
  • @Someprogrammerdude Yes! It's NOT valid after all! I gave the pointer as source which was freed by others! – user3498780 Nov 19 '17 at 16:34

0 Answers0