指针未指向 NULL 时的访问冲突

Access violation when pointer is not pointing to NULL

本文关键字:访问冲突 NULL 指针      更新时间:2023-10-16

这个小代码导致运行时错误,指出"访问冲突"。我在网上读到它说当指针指向 NULL 时,它的值无法更改。但这并没有解决问题。

#include<iostream>
using namespace std;
int max=3;
struct node
{
    char *ptr;
}*start, *current = start;
void init()
{
    current->ptr = (char*)malloc(max*sizeof(char)); //ERROR IN THIS LINE. 
}
void add(char page)
{
    char *c;
    c = current->ptr;
        if (page == *c)
            cout << "Yes";
        else
            cout << "No";
}
void main()
{
    init();
    add('a');
    cin >> max;
}

struct node
{
    char *ptr;
}*start, *current = start;

不创建节点结构,只创建指针。所以"当前"没有初始化。更改为

struct node
{
    char *ptr;
}start, *current = &start;

或添加 main() 或 init() 正确的内存分配

current = (node*)malloc(sizeof(node));

发生代码转储是因为您正在访问未初始化的指针。"current"应该初始化为有效的内存位置,然后再尝试 De - 引用它。更干净的代码将是

#include<iostream>
using namespace std;
int max=3;
struct node
{
    char *ptr;
};
struct node* start = new node();
struct node* current = start;
void init()
{
    current->ptr = (char*)malloc(max*sizeof(char)); //ERROR IN THIS LINE. 
}
void add(char page)
{
    char *c;
    c = current->ptr;
        if (page == *c)
            cout << "Yes";
        else
            cout << "No";
}
void main()
{
    init();
    add('a');
    cin >> max;
}