1

I am trying to run the program in Visual Studio 2013 The malloc function is not recognized, I don't know what header should I include if not cstring

#include <cstring>

float x[4] = { 1, 1, 1, 1 };
float y[4] = { 2, 2, 2, 2 };

float* total = malloc(8 * sizeof(float)); // array to hold the result

memcpy(total,     x, 4 * sizeof(float)); // copy 4 floats from x to total[0]...total[3]
memcpy(total + 4, y, 4 * sizeof(float)); // copy 4 floats from y to total[4]...total[7]
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Bobotic
  • 43
  • 1
  • 9
  • #include helped with malloc, memcpy still not recognised – Bobotic May 10 '16 at 15:42
  • 2
    `` is a C++ header (based on the standard C header ``). Are you compiling your code as C or as C++? – Keith Thompson May 10 '16 at 19:26
  • 1
    Possible duplicate of [What header should I include for memcpy and realloc?](https://stackoverflow.com/questions/2283712/what-header-should-i-include-for-memcpy-and-realloc) – jww Nov 30 '17 at 06:10

2 Answers2

4

The memcpy function is declared in <string.h>.

The malloc function is declared in <stdlib.h>.

Your system should have some documentation that tells you, for each library function, which header you need to #include to use it (and possibly what library you have to specify to link to it). (If you were on Unix or Linux, I'd suggest the man page.) Failing that, a web search for the function name will probably give you the information (though there's also plenty of bad information out there).

For MS Windows, MSDN has a lot of online documentation. For example, a Google search for "MSDN malloc" turns up this page -- which, unfortunately, also mentions the non-standard <malloc.h> header, without making it clear that it's non-standard.

A web search for "man malloc" will give you results that might be more Unix-specific, but for the standard functions that shouldn't be much of a problem.

Incidentally, <cstring> is a C++ header; it's the C++ version of C's <string.h>. If you want to write C code, be sure you're invoking your compiler as a C compiler. (Naming your source file with a .c extension is sometimes enough to do this.)

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
1

If you Google a standard library function you can usually find a page, such as this one, that will tell you which header to include.

#include <string.h>

void *memcpy(void *dest, const void *src, size_t n);

Richard Horrocks
  • 419
  • 3
  • 19