43

I am porting a project to the iPhone and it uses realloc and memcpy which are not found. What is the header to include?

It's a project mixing Objective C and C++ and I am starting to be lost.

Thanks in advance for your help!

jww
  • 97,681
  • 90
  • 411
  • 885
AP.
  • 5,205
  • 7
  • 50
  • 94

2 Answers2

61

In C:

#include <string.h> // memcpy
#include <stdlib.h> //realloc

In C++, remove the .h and prefix with a c. In C++, they will be placed in the std namespace, but are also global.

GManNickG
  • 494,350
  • 52
  • 494
  • 543
  • You could use `#ifdef __cplusplus` / `#else` to automatically include the correct ones for either C or C++. – cp.engr Jan 26 '17 at 20:56
  • If you don't mind polluting the global namespace, `string.h` and `stdlib.h` work in C++ just as well and you can keep using `realloc`, `memcpy` instead of `std::realloc`, `std::memcpy` etc., which seems to be more in line with what the original poster wanted. – tobi_s Oct 10 '18 at 09:14
8

In C++ it's more idiomatic to use std::copy than C's memcpy, although the latter does work just as well. To get std::copy, you need to #include <algorithm>.

There's not a direct C++ equivalent to realloc, though.

Tyler McHenry
  • 74,820
  • 18
  • 121
  • 166
  • 2
    If I could mark this answer as not useful with a comment, I would do so because it is incorrect. As GMan said, realloc is found in . – David Harris Feb 17 '10 at 21:35
  • 5
    I did not say that it is not possible to use the C standard library function `realloc` in C++ (since, of course, the C++ standard library includes the entirety of the C89 standard library). I said that there is not a new C++ standard library function that encompasses the functionality of `realloc` as `std::copy` does for `memcpy`. Although I suppose my intent is not obvious if my answer is read in isolation as opposed to in conjunction with the other, already accepted answer. – Tyler McHenry Feb 17 '10 at 21:54