There's no need to allocate this vector for every scanline (and free it, AND copy the contents to data).  You are given the data pointer, why not do the work straight there:

    unsigned char *outscanline = (unsigned char *)data;
    ... everything else as you have it ...
    ... but eliminate the memcpy and clear at the end