malloc 强制类型转换

//以下关于malloc的讲解及代码来自MSDN

malloc

Allocates memory blocks.

void *malloc( size_t size );

Routine

Required Header

Compatibility

malloc

and <malloc.h>

ANSI, Win 95, Win NT

Return Value

malloc returns a void pointer to the allocated space, or NULL if there is insufficient memory available.

To return a pointer to a type other than void, use a type cast on the return value.

The storage space pointed to by the return value is guaranteed to be suitably aligned for storage of any type of object.

 If size is 0, malloc allocates a zero-length item in the heap and returns a valid pointer to that item.

 Always check the return from malloc, even if the amount of memory requested is small.

Parameter

size

Bytes to allocate

Remarks(备注,附注)

The malloc function allocates a memory block of at least size bytes. The block may be larger than size bytes because of space required for alignment and maintenance information.

 

Example:

/* MALLOC.C: This program allocates memory with * malloc, then frees the memory with free. */ #include /* For _MAX_PATH definition */ #include #include void main( void ) { char *string; /* Allocate space for a path name */ string = malloc( _MAX_PATH ); if( string == NULL ) printf( "Insufficient memory available/n" ); else { printf( "Memory space allocated for path name/n" ); free( string ); printf( "Memory freed/n" ); } }  

  

当上述代码段(摘自MSDN)以mallocDemo.c命名时,运行正常,结果为:

Memory space allocated for path name Memory freed Press any key to continue

但以mallocDemo.cpp命名时,编译报错:

.cpp(14) : error C2440: '=' : cannot convert from 'void *' to 'char *' Conversion from 'void*' to pointer to non-'void' requires an explicit cast

 

解决方法:

第14行修改为string = (char *)malloc( _MAX_PATH );

 

原因:

C中对指针类型转换的检查没有C++那么严格

参考:http://www.programfan.com/club/showpost.asp?id=22954

你可能感兴趣的:(malloc 强制类型转换)