您的位置:首页 > 编程语言 > C语言/C++

关于c++悬垂指针的问题

2016-01-27 15:22 573 查看
分析在下面

此处代码为验证猜测代码

#define NDEBUG

#include <stdio.h>

#include <stdlib.h>

#include <memory>

#include <list>

#include <vector>

#include <boost/shared_ptr.hpp>

#include <sys/types.h>

#include <string.h>

#include <map>

#include <unordered_map>

#include <time.h>

#include <sys/wait.h>

#include <netdb.h>

#include <arpa/inet.h>

using namespace std;

#define MAX_LENGTH 30

#include <string.h>

#include <sys/socket.h>

#include <sys/ioctl.h>

#include <net/if.h>

#include <stdio.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <stdio.h>

#include <sys/types.h>

#include <ifaddrs.h>

#include <netinet/in.h>

#include <string.h>

#include <arpa/inet.h>

#include <unistd.h>

#include <signal.h>

#include <sys/param.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

#include <sys/wait.h>

#define MAXFILE 65535

#define SIZE (sizeof(int) + 4)

#include <signal.h>

#define MAXLINE 20

#define NDEBUG

#define BUFFER_SIZE 128

#define SRC_FILE_NAME "src_file.txt"

#define DEST_FILE_NAME "dest_file.txt"

#define OFFSET 0

#include <functional>

#include <iostream>

#include <mysql/mysql.h>

typedef unsigned char BYTE;

class chapter

{

public:

chapter()

{

}

~chapter()

{

}

public:

std::map<int32_t, int32_t> mm;

void package()

{

printf("chapter!!!\n");

}

};

class user

{

public:

user()

{

_chapter = new chapter();

}

~user()

{

if (_chapter != nullptr)

{

delete _chapter;

_chapter = nullptr;

}

}

public:

chapter* _chapter = nullptr;

};

class token

{

public:

token()

{

}

~token()

{

}

public:

user _user;

};

class user_data_manager

{

public:

user_data_manager()

{

}

~user_data_manager()

{

}

public:

user* _user;

};

int main()

{

token* _token = new token();

user_data_manager _user_data_manager;

_user_data_manager._user = &(_token->_user);

delete _token;

_user_data_manager._user->_chapter->package();

while(true);

return 0;

}

=======================================================================================================================

在编程过程中悬垂指针误用给程序员调试带来了很大的困扰现在总结如下:

1:造成指针误用,有两种情况,一种是使用了未初始化的指针,第二种是指针指向的对象已经不存在,也叫做悬垂指针

2:怎样快速分辨这两种情况,还是有一些小技巧在里面的,现在罗列如下:

(1)在查看core文件时如果是在调用指针的时候崩溃说明你使用了未初始化的指针,这也是最容易辨别出来的

如代码: User* _user = null;

user->fight();

在栈轨迹上会崩溃user->fight()这一行。相信大家很容易解决这种bug

(2) 在查看core文件时,如果崩溃到在引用一个对象的成员变量(如非指针成员变量)时,正常的逻辑是绝对合法的,

此时说明你使用了悬垂指针, 此时你会发现该对象的this指针是有值的,而且看起来是合法的,但却在使用该对象的数据成员时崩溃,

注意如果使用的仅仅是该对象的一个函数且该函数没有使用任何数据成员,仅仅是打印输出,如printf("run here!!") 程序是不会崩溃的。

3:怎样避免使用悬垂指针。

现在分享以下自己的理解:在有多个指针指向同一个对象时,在该对象被delete释放时,即使将指向该对象的所有指针设为null,并在使用该指针的时候先判空

再使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: