0

I have a smart pointer defined like this

     auto ptr = make_shared<int[]>(5);

and another array

    int arr[] = {1,2,3,4,5};

I want to copy data in arr to ptr, I tried using this

    memcpy(ptr.get(), arr, 5 * sizeof(int))

But when I try printing like this

    for (int i = 0; i < 5; i++) {
        std::cout<<ptr[i]<<std::endl;
    }

I get

malloc(): corrupted top size

Process finished with exit code 134
(interrupted by signal 6: SIGABRT)

Is there something wrong with the ptr initialization ?

heyloo
  • 35
  • 3
  • 3
    `memcpy(ptr.get(), arr, 5*sizeof(int));` – Alex F Jan 19 '23 at 06:42
  • 1
    Because you're copying 5 bytes instead of 5 elements of type int. – Captain Obvlious Jan 19 '23 at 06:42
  • @AlexF with this i get `malloc(): corrupted top size` – heyloo Jan 19 '23 at 06:45
  • I cannot reproduce your malloc corruption. See [godbolt here](https://godbolt.org/z/4zh1s5K3P). Please post the entire code to reproduce this – Homer512 Jan 19 '23 at 06:52
  • [Not reproduced](https://godbolt.org/z/r38TEW51x) – pptaszni Jan 19 '23 at 06:54
  • @Homer512 what does this produce on your pc then ` auto ptr = make_shared(); int arr[] = {1,2,3,4,5}; std::memcpy(ptr.get(),arr,5*sizeof(int)); for (int i = 0; i < 5; i++) { std::cout< – heyloo Jan 19 '23 at 06:55
  • `make_shared()`is not what you posted in your question. – Homer512 Jan 19 '23 at 06:56
  • I can reproduce it in GCC using onlinegdb. If I access any element of the shared pointer prior to memcpy, the issue goes away. – Dmitry Kuzminov Jan 19 '23 at 06:56
  • @Homer512 which is the correct way – heyloo Jan 19 '23 at 06:58
  • @DmitryKuzminov I am using gcc yes – heyloo Jan 19 '23 at 06:58
  • 2
    `make_shared` for array types is part of the experimental C++20 support in GCC-12. See [the release notes](https://gcc.gnu.org/gcc-12/changes.html) It fails on GCC-11 and earlier in my tests – Homer512 Jan 19 '23 at 07:02
  • 2
    Have you looked at [std::copy](https://en.cppreference.com/w/cpp/algorithm/copy)? It is the (typesafe) C++ equivalent of memcpy and it will [not be slower](https://stackoverflow.com/questions/4707012/is-it-better-to-use-stdmemcpy-or-stdcopy-in-terms-to-performance). – Pepijn Kramer Jan 19 '23 at 07:12
  • 2
    The workaround for missing `make_shared`support is `std::shared_ptr(new int[5])`. Less efficient but compatible with C++17 and works with GCC-7 and up – Homer512 Jan 19 '23 at 07:26

0 Answers0