C和C++规定,函数返回的指针不应该被修改(不可修改地址,不能成功free)。

#include <iostream>
#include <vector>
#include <iterator>
#include <stdio.h>
using namespace std;

typedef struct _Node
{
    unsigned char num;
}Node;

class Test
{
public:
    Test()
    {
        m_node = new Node;
        m_node->num = 10;
    }
    Node *getm_node()
    {
        return m_node;
    }
    void Free()
    {
        delete m_node;
    }
private:
    Node *m_node;
};

int main()
{
    puts("");

    Test test;
    printf( "num: %d\n", test.getm_node()->num ); //num: 10

    //test.getm_node() = 0x0; // the pointer returned can't be written.

    //Not works.
    delete test.getm_node();
    printf( "num: %d\n", test.getm_node()->num ); //num: 10

    //malloc: pointer being freed was not allocated
    test.Free();
    printf( "num: %d\n", test.getm_node()->num );
    return 0;
}

分类: C plus plus

发表评论

电子邮件地址不会被公开。 必填项已用*标注