Why am I getting "Using the undeclared identifier" malloc "?

I am experimenting with Xcode and trying to compile another user code.

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 the header file.

He calls me on

Using the undeclared identifier 'malloc'

And also for strlen, memcpy and for free.

What's happening? Sorry if this is very simple, I am new to C and C ++

+7
source share
2 answers

Xcode tells you that you are using something called malloc, but do not know 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 starting with C # are pre-processor commands. In this example, the #include command retrieves the contents of another file. It will be like you entered the contents of stdlib.h yourself. If you right-click on the #include line and select "go to definition", Xcode will open stdlib.h. If you search stdlib.h, you will find:

 void *malloc(size_t); 

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

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

+18
source

Before using these features, you must include header files that provide their prototype.

for malloc and free:

 #include <stdlib.h> 

for strlen and memcpy this is:

 #include <string.h> 

You also mention C ++. These functions are taken from the standard C library. To use them from C ++ code, the include lines will be as follows:

 #include <cstdlib> #include <cstring> 

However, you may be doing something different in C ++ and not using them.

+4
source

All Articles