Prasanth Kumar Arisetti Prasanth Kumar Arisetti - 2 months ago 17
C++ Question

Memory Collision of Local Variables of Two Funcions

I have Functions. FunctionA and FunctionB.

in FunctionA
{
char *m; //Pointed to Shared Memory A
char outa[600000]
//Coping the Data into another character array
memcpy(out, m, 6000000);
// Now Processing this Data,
// After Processing I am storing this data.
}

in FunctionB
{
char *m; //Pointed to Shared Memory B
char outb[600000]
//Coping the Data into another character array
memcpy(out, m, 6000000);
// Now Processing this Data,
// After Processing I am storing this data.
}


Now in main, I am creating a thread function which continuously call functionA and functionB, one after the other.

But, sometimes functionA out buffer is getting, while reading functionB out buffer.

But, When i moved those two buffers as member variables of a class, Then there is no Problem of memory collision.

Why it Happened in the First case?
What is the wrong i had done?

Answer

As pointed out by @RevolverOcelot, please provide MWE. Also, both 'm' pointers are uninitialized. Reserve memory of correct size and then use memcpy.

For example:

char *m = new char[600000];

...

memcpy(out, m, 6000000);

in both functions. Remember to free allocated memory.

Comments