Search code examples
cmallocdeclarationparenthesesvariable-declaration

Adding brackets around the type of the return value from malloc


When I hope to allocate some memory using malloc, I tried doing it in the following ways:

(char *) conc_str = (char *) malloc(1);
char *conc_str2 = (char *)malloc(1);

However, the first one gives me an error saying that "identifier "conc_str" is undefinedC/C++(20)". Why does it throw an error while the 2nd way of mallocing memory doesn't? What's the difference between using (char *) vs using char *?


Solution

  • This line:

    (char *) conc_str = (char *) malloc(1);
    

    Is a statement which performs a cast on an existing variable called conc_str and attempts to assign a value to the result of the cast. This is invalid for two reasons: conc_str has not yet been defined and the result of a cast cannot be assigned to.

    While this line:

    char *conc_str2 = (char *)malloc(1);
    

    Is a definition for the variable conc_str2, specifying char * as its type, and initializes it with the value returned by malloc.

    Also, you shouldn't cast the return value of malloc as it's not required and can mask other problems in your code.