Why do we need to do what malloc returns?

int length = strlen(src); char *structSpace = malloc(sizeof(String) + length + 1); String *string = (String*) structSpace; int *string = (int*) structSpace; 

* I created a String structure

+6
c heap malloc
source share
7 answers

Not. void* will implicitly display everything you need in C. See also the C FAQ on why you would like to explicitly avoid casting the malloc return to Answer C. @ Sinan further illustrates why this happened inconsistently.

+15
source share

Since malloc returns a pointer to void, i.e. just allocates pieces of memory, not paying attention to the data that will be stored there. In C ++, your returned void * will not be implicitly cast to a pointer of your type. In your example, you did not specify which malloc returned. Malloc returned a void * that was implicitly cast to char *, but on the next line you are ... ok, that no longer makes sense.

+6
source share

C's list of frequently asked questions is an invaluable resource: Why does some code carefully discard the values ​​returned by malloc on a highlighted pointer type? .

+6
source share

This is one of the few problems that makes the statement “C ++ - a superset of C” not entirely true. In C, the void pointer can be implicitly applied to any other type of pointer. However, C ++ is more stringent with type safety, so you need to explicitly point the return value of malloc to the appropriate type. This is usually not a big problem, because C ++ code tends to use new rather than malloc , which does not require type casting.

+3
source share

In C, dropping the result from malloc is not required and should not be performed. This can lead, for example, to the error with the #include <stdlib.h> error, so you do not have a prototype for malloc in scope. This, in turn, can lead to other errors and a lack of tolerance (although the worst offenders in this regard are now mostly outdated).

In C ++, you must specify the result of malloc to assign it to a pointer to any type other than void. However, if you really don't need to write code that can be compiled as C or C ++, you should generally avoid using malloc in C ++ and allocate memory with new .

+2
source share

You usually see this C code from beginners (or C ++ coders :-)):

 int main() { int len = 40; char *my_string = (char *) malloc(sizeof(char)*len); return 0; } 

It is not necessary and evil, you can avoid useless casting by including stdlib.h

 #include <stdlib.h> int main() { int len = 40; char *my_string = malloc(sizeof(char)*len); return 0; } 
+1
source share

You should think hard about casting after using the malloc command, as it provides greater portability and greater compatibility with other parts of your program. If you do not, you may risk incompatible data types that could lead to errors.

0
source share

All Articles