C + + misunderstanding three: cast the return value of malloc ()

Source: Internet
Author: User
Tags include

The first thing to say is that you use the malloc function to include stdlib.h (Cstdlib in C + +), not malloc.h. Because Malloc.h never appeared in C or C + + standards! So not all compilers have malloc.h this header file. But all C compilers should have stdlib.h this header file.

In C + +, the return value of the cast malloc () is required, otherwise it cannot be compiled. In C, however, this cast is redundant and is not conducive to code maintenance.

At first, C did not have a void pointer, when char* was used as a generic pointer (generic pointer), so malloc's return value was char* at that time. Therefore, the return value of malloc must be cast. Later, the ANSI C (i.e. C89) standard defines void pointers as new generic pointers. A void pointer can be assigned directly to any type of pointer (except for function pointers) without conversion. From then on, the return value of the malloc becomes void*, and there is no need to cast the malloc return value. The following program compiles correctly through VC6.

#include <stdlib.h>
int main( void )
{
 double *p = malloc( sizeof *p ); /* 不推荐用 sizeof( double ) */
 free(p);
 return 0;
}

Of course, the cast malloc return value is not wrong, but the superfluous! For example, you might change double *p to int *p in the future. At this point, you will change all the related (double *) malloc (sizeof double) to (int *) malloc (int). If you change the leak, then your program is a bug. Even if you are sure to get rid of all the relevant statements, but this boring job you will not like it! You can avoid such problems without using a cast, and it's easy to write. Using the following code, no modifications are necessary, regardless of the type of pointer to be changed later.

Double *p = malloc (sizeof *p);

Similarly, you do not need to cast the return value if you use Calloc, realloc, and so on to return a function of void*.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.