Alex Rivera | Logout

Why am I getting "Use of undeclared identifier 'malloc' " ?

Asked 2012-09-03T01:00:33.327
8

I'm experimenting with XCode and trying to compile someone else's Windows code.

There's this:

inline GMVariable(const char* a) {
    unsigned int len = strlen(a);
    char *data = (char*)(malloc(len+13));
    if(data==NULL) {
    }
    // Apparently the first two bytes are the code page (0xfde9 = UTF8)
    // and the next two bytes are the number of bytes per character (1).
    // But it also works if you just set it to 0, apparently.
    // This is little-endian, so the two first bytes actually go last.
    *(unsigned int*)(data) = 0x0001fde9;
    // This is the reference count. I just set it to a high value
    // so GM doesn't try to free the memory.
    *(unsigned int*)(data+4) = 1000;
    // Finally, the length of the string.
    *(unsigned int*)(data+8) = len;
    memcpy(data+12, a, len+1);
    type = 1;
    real = 0.0;
    string = data+12;
    padding = 0;
}

This is in a header file.

It calls me out on

Use of undeclared identifier 'malloc'

And also for strlen, memcpy and free.

What's going on? Sorry if this is painfully simple, I am new to C and C++

Edit
Report

1 Answer

10

Prior to using these functions, you should include the header files that provide their prototype.

for malloc & free it is:

#include <stdlib.h>

for strlen and memcpy it is:

#include <string.h>

You also mention C++. These functions are from the C standard library. To use them from C++ code the include lines would be:

#include <cstdlib>
#include <cstring>

However, you might well be doing things differently in C++ and not be using these.

answered 2012-09-03T01:09:26.210

Your Answer