Home > Software engineering >  Why is my memory copy not working properly?
Why is my memory copy not working properly?

Time:05-31

I'm running into a runtime error when performing a simple memory copy. I've tried debugging with GDB but I'm still lost on why this behavior is occurring.

#include <iostream>
#include <string>



int main()
{
  
  int v1[3] = {1, 2, 3};
  int* p1 = v1;
  
  int v2[3] = {10, 9, 8};
  int* p2 = v2;
  
   for (int i = 0; i < sizeof(v1)/sizeof(v1[0]); i  ) {
    *p2   = *p1  ;

  }

    for (int i = 0; i< sizeof(v1)/sizeof(v1[0]); i  )  {      
      std::cout<< "p1: " << *p1   << " and p2: " << *p2   << std::endl;

    }
}

The output:

p1: 0 and p2: 1
p1: 3 and p2: 2
p1: 373291268 and p2: 3

CodePudding user response:

You never reset your pointers p1 and p2 between the two loops. At the start of the second loop, they're both at one-past-the-end (which is not UB but can't be dereferenced safely). Then you them both once and at that point they are pointers to memory you don't control, which is UB.

CodePudding user response:

You did not reset the pointers p1 and p2 after the first for loop

for (int i = 0; i < sizeof(v1)/sizeof(v1[0]); i  ) {
 *p2   = *p1  ;

}

Si using these pointers that now points after last elements of the arrays in the second for loop invokes undefined behavior.

The reason of the mistake is that you are not defining the variables in minimum scopes where they are used.

Pay also attention to that the header <string> is redundant because neither declaration from the header is used in your program.

You could write your program the following way.

#include <iostream>

int main()
{
    const size_t N = 3;
    int v1[N] = {1, 2, 3};
    int v2[N] = {10, 9, 8};

    for ( int *p1 = v1, *p2 = v2; p1 != v1   N;   p1,   p2 ) 
    {
        *p2 = *p1;
    }

    for ( const int *p1 = v1, *p2 = v2; p1 != v1   N;   p1,   p2 )  
    {      
        std::cout << "*p1: " << *p1 << " and *p2: " << *p2 << std::endl;
    }
}
  • Related