0

I am completely lost on why memcpy or memmove is not working for me.

I am trying to copy a array of struct (joblist) to another array of same struct (Q) to use for data manipulation, while keeping my original array intact.

I have spent a lot of time on SO and google troubleshooting this and I cannot find out why it won't work.

    Q = new AdjacencyList[numjobs + 1]; //create a queue
    // Q = joblist;
    memmove(&Q, &joblist, sizeof(AdjacencyList) );
    Q[0].jobnum = 30;

I tried to just make Q = joblist, but then when I changed a value in one, it changed in both.

    struct AdjacencyList  {
    NodeType state; // what is present state of job? 
    NodePath path; // is job part of critical path?
    int jobnum;
    int edges;     
    int tocount;
    int fromcount;          
    int to[50];      
    int from[50]; 
    };
    AdjacencyList *joblist;
    AdjacencyList *Q;

This is the struct I created.

*** Error in `p5.out': corrupted double-linked list: 0x0989e8c0 ***
======= Backtrace: =========
/lib/libc.so.6[0x47975143]
/lib/libc.so.6[0x4797b984]
/lib/libc.so.6[0x4797cd28]
/lib/libstdc++.so.6(_ZdlPv+0x20)[0x47d8d9e0]
/lib/libstdc++.so.6(_ZdaPv+0x1c)[0x47d8da3c]

Any help would be greatly appreciated. Thanks.

SUB

subcan
  • 2,021
  • 2
  • 18
  • 21
  • If `joblist` and `Q`were `std::vector` you wouldn't have to mess around with either `new` or `memcpy`. – user657267 Mar 11 '15 at 05:06
  • I would use a vector but this is a university data-structures assignment and we are not allowed to use anything from STL. Thanks for your comment – subcan Mar 11 '15 at 05:11

2 Answers2

2

They way you call memmove(dst, src, sizes). Is not correct. It should be

memmove(Q, joblist, sizeof(AdjacencyList) * (numjobs + 1));

UPDATE:

Like its name, memmove operates on memory. It simply copies sizes bytes data from src to dst.

If you want to copy an array of n objects to Q, you must tell the function the total size of the data you want to copy, that is size of each objects * number of objects. I don't know how many objects you need to copy, numjobs + 1 is only an example. If you want to copy numjobs it should be sizeof(AdjacencyList) * numjobs.

Qmick Zh
  • 555
  • 3
  • 8
  • Thank you so much. I have pulled every last hair out on this one. Can you tell me why the * (numjobs + 1)? – subcan Mar 11 '15 at 05:10
1
memmove(&Q, &joblist, sizeof(AdjacencyList) );

is wrong and results in undefined behavior. It copies sizeof(AdjacencyList) bytes from the address of joblist to the address of Q.

What you need to use is:

memmove(Q, joblist, sizeof(AdjacencyList) );

to copy one object from joblist to Q. If you want to copy numjobs + 1 objects, you need to use:

memmove(Q, joblist, sizeof(AdjacencyList)*(numjobs + 1));
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Thanks for the reply. You guys are all so helpful. I understand now why the * (numjobs + 1). Makes a world of sense. – subcan Mar 11 '15 at 05:16