8

不建议用memset初始化指针

 3 years ago
source link: https://www.maixj.net/ict/memset-24260
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

不建议用memset初始化指针

2020年12月29日 / 1次阅读CC++

一般情况下,给空指针赋值为NULL,初始化一块内存,用memset为0。

如果内存块中有的字段是指针,此时就要注意了。虽然NULL一般情况下就是0,但是不排除也有特别的时候,特别是在写跨平台代码的时候,不要有这种默认思维。

应该老老实实的给指针赋值NULL,值数据memset为0。

如果一个个给指针赋值NULL太费劲,可能是代码结构有问题,也可以考虑不初始化,用后面的代码逻辑去保证。

'\0'字符为null字符,是字符串的结束符,在ASCII中排第1位,值就是0x00。

可以用 memset 函数来得到一个空指针吗?

这个问题等同于:如果 p 是一个指针变量,那么

memset( &p, 0, sizeof(p) ); 和 p = 0;

是等价的吗?

答案是否定的,虽然在大多数系统上是等价的,但是因为有的系统存在着“非零空指针” (nonzero null pointer),所以这时两者不等价。由于这个原因,要注意当想将指针设置为空指针的时候不应该使用 memset,而应该用空指针常量或空指针对指针变量赋值或者初始化的方法。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK