-1

In the below loop, I am attempting to copy data stored at the address of voidPtr. The data here is known to be an integer array of length count. I've read that casting this array to an int and then performing the copy (as shown below) should work.

int intArr[count];
  for (int i = 0; i<count; i++){
    intArr[i] = ((int*) voidPtr)[i];
  }

However, when I attempt to print the array int by int, I am receiving a seg-fault.

  for (int i = 0; i<count; i++){
    printf("%d ", intArr[i]);
  }

Any ideas?

mongolol
  • 941
  • 1
  • 13
  • 31
  • 2
    First, you should just `memcpy(intArr, voidPtr, count * sizeof(int));` for the copy (it's simpler and more efficient). Second, could you please post more code. What you showed doesn't seem to contain particular errors. – maddouri Oct 22 '15 at 21:21
  • As mentioned by @865719, you need to provide a complete example that shows the problem. The code above would work if all your assumptions are correct (for which you've not provided the code). [Here](http://cpp.sh/8aqh) is an example. You may also want to reconsider your design as using `void*` to pass other types is not a good design practice and can easily get you in trouble. – crayzeewulf Oct 22 '15 at 21:26
  • @865719, using a malloc and memcpy resolved the issue. I'm assuming the container size I created wasn't big enough. Hugely appreciate the suggestion, and I will try to be a little more thorough on future posts. – mongolol Oct 22 '15 at 21:37
  • @mongolol *using a malloc and memcpy resolved the issue* -- That isn't a solution if you do not know exactly why this "resolved the issue". All you may have done is mask the bug, but the bug is still there. Assuming you are using variable-length arrays (C++ doesn't have these, BTW), your code should have worked. You probably have a bug somewhere else that is affecting this code. – PaulMcKenzie Oct 22 '15 at 21:39
  • @Paul I'll have to troubleshoot it further. – mongolol Oct 22 '15 at 21:49
  • Resolved the issue. I only posted what I thought was causing the problem, it was actually a error on the particular MPI process. (There's a LOT more to this than I showed. My fault.) – mongolol Oct 23 '15 at 00:50

1 Answers1

0

You are doing wrong stuff, and when compiler warned you, you just shut it up with the cast. No you've shoot yourself in the foot, and who is to blame? :)

What you did was to say that voidPtr now becomes an int*, and please access it's element i. This can't be correct. Most likely, on your system void* is not the same as int*, so with this cast you will be accessing incorrect elements. Also, your void* does not seem to point to the big enough location - this is what causing the crash.

Do not use void* in C++, do not cast.

SergeyA
  • 61,605
  • 5
  • 78
  • 137