Question

This small code is causing a runtime error saying "Access Violation". I read about it online which says that when a pointer is pointing to NULL, its value cannot be changed. But that didn't solve the problem.

#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;
}
Was it helpful?

Solution 2

The code dump happens because you are accessing a pointer which is not initialized . "current" should be initialized to a valid memory location before trying the De - referencing it . more cleaner code would be

#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;
}

OTHER TIPS

This

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

not creates node struct, only pointer. So "current" is not initialized. Change to

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

or add in main() or in init() correct memory allocation

current = (node*)malloc(sizeof(node));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top