指针未指向 NULL 时的访问冲突
Access violation when pointer is not pointing to NULL
这个小代码导致运行时错误,指出"访问冲突"。我在网上读到它说当指针指向 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;
}
相关文章:
- 写入位置0x0000000C时发生访问冲突
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 链表中写入访问冲突的未知原因
- C++中的openCV Mat访问冲突
- C++尝试深度复制唯一指针时出现内存访问冲突
- C++ 中动态二维数组的访问冲突
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- 写入访问冲突异常
- 在类 12.exe 中0x7B37FF80 (ucrtbased.dll) 引发异常: 0xC0000005:访问冲突读
- 0xC0000005:访问冲突写入位置0xCDCDCDCD动态分配错误
- 读取访问冲突.这0xCDCDCDCD
- 0xC0000005:访问冲突读取位置 0x00000000. 重载 == 运算符的问题
- 插入数组时违反写访问冲突
- 使用 ReadProcessMemory 获取字符串值的访问冲突
- 尝试通过共享指针使用变量时读取访问冲突
- 堆栈上的 C++ 访问冲突写入异常
- 引发异常:写访问冲突. temp 为 nullptr
- cv::resize() 失败并出现访问冲突错误(由 NULL> 处的 <struct 引起)
- 指针未指向 NULL 时的访问冲突
- 当第 4 个(可选)参数为 NULL 时,写入文件将引发访问冲突