new 之后 需不需要 memset?
比如char* pCh = new char[100];
后面需不需要memset(pCh, 0, 100);
调用了memset有哪些好处?不调用,又有什么潜在的危险?
请帮忙分析一下。。。
[解决办法]
我从来不用
[解决办法]
memset
Sets buffers to a specified character.
void *memset( void *dest, int c, size_t count );
Routine Required Header Compatibility
memset <memory.h> or <string.h> ANSI, Win 95, Win NT
For additional compatibility information, see Compatibility in the Introduction.
Libraries
LIBC.LIB Single thread static library, retail version
LIBCMT.LIB Multithread static library, retail version
MSVCRT.LIB Import library for MSVCRT.DLL, retail version
Return Value
memset returns the value of dest.
Parameters
dest
Pointer to destination
c
Character to set
count
Number of characters
Remarks
The memset function sets the first count bytes of dest to the character c.
Example
/* MEMSET.C: This program uses memset to
* set the first four bytes of buffer to "* ".
*/
#include <memory.h>
#include <stdio.h>
void main( void )
{
char buffer[] = "This is a test of the memset function ";
printf( "Before: %s\n ", buffer );
memset( buffer, '* ', 4 );
printf( "After: %s\n ", buffer );
}
Output
Before: This is a test of the memset function
After: **** is a test of the memset function
[解决办法]
看情况。比如
char* pCh = new char[100];
snprintf(pCh,,99, "%s ", "aaaaaaaaaa ");这样就不需要了
[解决办法]
就是不知道new这个动作,到底做了哪些事情?
需不需要memset?
---------------------------
new 就是分配了一些空间,别的没干什么,用这块空间干啥是你自己决定的,要不要memset也是你自己决定的,一般来讲不需要memset,memset和new之间没有任何联系
[解决办法]
如果是自定义的struct/class,应该使用构造函数。如果是内建数据类型,比如int,应该memset。
当然,更好的建议是使用vector取代new出来的数组。
[解决办法]
基本没memset过..
[解决办法]
和new不new的没关系,是变量必须赋初值 这个编程规范。违背了的,迟早要吃苦头。
[解决办法]
比如char* pCh = new char[100];
后面需不需要memset(pCh, 0, 100);
调用了memset有哪些好处?不调用,又有什么潜在的危险?
请帮忙分析一下。。。
=================================
好处就是初始化
如果不初始化的话,可能会出现内存重叠使用的情况(注意是可能)
所以最好要初始化
[解决办法]
数组也要么?
数组还是不用的好.
[解决办法]
如果new char[100]之后进行Memset是必要的,因为内建类型new之后的取值是未定义的,不memset很危险。
如果new Class[100]之后,Memset就比较危险了,因为Class在New的时候会调用构造函数,没必要调用memset
[解决办法]
new之后初始化是个好习惯,除非你后面紧跟着用sprinf函数而不是用strcat