Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

xcode

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++

like image 394
Name McChange Avatar asked Sep 03 '12 01:09

Name McChange


1 Answers

XCode is telling you that you're using something called malloc, but it has no idea what malloc is. The best way to do this is to add the following to your code:

#include <stdlib.h> // pulls in declaration of malloc, free
#include <string.h> // pulls in declaration for strlen.

In C and C++ lines that start with # are command to the pre-processor. In this example, the command #include pulls in the complete contents of a another file. It will be as if you had typed in the contents of stdlib.h yourself. If right click on the #include line and select "go to definition" XCode will open up stdlib.h. If you search through stdlib.h you'll find:

void    *malloc(size_t);

Which tells the compiler that malloc is a function you can call with a single size_t argument.

You can use the "man" command to find which header files to include for other functions.

like image 185
razeh Avatar answered Sep 25 '22 23:09

razeh