jdscardoso
jdscardoso

Reputation: 291

memcpy "unhandled exception" "access violation reading location"

I am using an array of structs to store different binary data, from different clients. While I am debugging, I can do a few iterations with success (in memcpy). But at some point the debug crashes with "unhandled exception".

struct Buffer {
    int size_ = 0;
    int capacity_total = 200000;
    int beg_index = 0
    int end_index = 0;
    char data_[200000];
} buffer_audio[3];

int writing_bufer(Buffer& buffers, const char *data, int nbytes) {
    if (nbytes == 0) return 0;

    int capacity = buffers.capacity_total;

    if (nbytes <= capacity - buffers.end_index)
    {
        memcpy(buffers.data_ + buffers.end_index, data, nbytes); //crashes here
        buffers.end_index += nbytes;
        if (buffers.end_index == capacity) printf("full");
    }
    else { 
        return 0; }

    return buffers.end_index;
}

The buffer never is full or close of that. The full routine:

void buffering(const FunctionCallbackInfo<v8::Value>& args) {
    Isolate* isolate = Isolate::GetCurrent();
    HandleScope scope(isolate);

    int size = args[1]->NumberValue();
    int final_read = args[2]->NumberValue();
    int client_id = args[3]->NumberValue();
    int nbytes = args[4]->NumberValue();

    (...)
    buf = node::Buffer::Data(bufferObj);
    buffering_mem(buf,size, final_read, client_id,nbytes);


    Local<String> devolve = String::NewFromUtf8(isolate, "buffering_com_sucesso");//C++--->JS
    args.GetReturnValue().Set(devolve);
}

void buffering_mem(char* chunk,int size_chunk, int close_file, int client, int total_size){

    int check_bytes = writing_bufer(buffer_audio[client], chunk, size_chunk);
    //other code}

Upvotes: 0

Views: 3631

Answers (2)

jdscardoso
jdscardoso

Reputation: 291

With the huge help of @JSF

void buffering_mem(char* chunk,int size_chunk, int close_file, int client, int total_size){ 
    //old place of invocation
    if (close_file == 3) {

        fp0 = fopen("buffer_inteiro", "wb");
        fwrite(buffer_audio[client].data_, 1,total_size,fp0);
        fflush(fp0); return;
    }
    int check_bytes = writing_bufer(buffer_audio[client], chunk, size_chunk);

}

Upvotes: 0

JSF
JSF

Reputation: 5321

You are copying the wrong amount in your code:

memcpy(buffers.data_ + buffers.end_index, data, buffers.end_index+nbytes);

That should be just

memcpy(buffers.data_ + buffers.end_index, data, nbytes);

Upvotes: 5

Related Questions