1

I'm trying to do a basic text editor with linked lists for school project. When i tried to take a letter from keyboard program crushed cause of a runtime error. I watched currentLine->headLetter which is in void insertLetter function with debugger it says cannot access memory at address 0x8. I couldnt understand why it is crushing?

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>

struct sentence {
    struct sentence *next;
    struct sentence *prev;
    char letter;
};

struct sentence *currentLetter;

struct line{
    struct line *next;
    struct line *prev;
    struct sentence *headLetter;
    struct sentence *lastLetter;
};

struct line *headLine;
struct line *lastLine;
struct line *currentLine;

void gotoxy(int x, int y)
{
  static HANDLE h = NULL;
  if(!h)
    h = GetStdHandle(STD_OUTPUT_HANDLE);
  COORD c = { x, y };
  SetConsoleCursorPosition(h,c);
}

void insertFirstLine ()
{
   struct line *link = (struct line*) malloc(sizeof(struct line));

   headLine = lastLine = currentLine;
   headLine = link;
   link->prev = NULL;
   link->next = NULL;
}

void insertLetter (char data)
{
    struct sentence *link = (struct sentence*) malloc(sizeof(struct sentence));
    link->letter = data;

        currentLine->headLetter = link;
        currentLine->lastLetter = link;
        currentLetter = link;
        link->next = NULL;
        link->prev = NULL;

}

void newFile ()
{
    char control;
    while (1)
    {
        control = _getch();
        insertLetter(control);
    }
}

int main ()
{
    insertFirstLine();
    newFile();
    return 0;
}
  • 1
    This error message usually means you used `->` on a null pointer – M.M Dec 14 '16 at 23:49
  • [don't cast malloc in C](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Barmar Dec 14 '16 at 23:50
  • 1
    In `currentLine->headLetter = link;` , `currentLine` is a null pointer. – M.M Dec 14 '16 at 23:50
  • 1
    Maybe instead of `headLine = lastLine = currentLine;` you meant `headLine = lastLine = currentLine = link;` ? – M.M Dec 14 '16 at 23:51
  • I changed that line as you suggest and it worked thanks and also thanks for warning about casting malloc – yagizKanbur Dec 15 '16 at 00:21

1 Answers1

0

This error message usually means you used -> on a null pointer

In currentLine->headLetter = link; , currentLine is a null pointer.

Maybe instead of headLine = lastLine = currentLine; you meant headLine = lastLine = currentLine = link; ? – M.M

Armali
  • 18,255
  • 14
  • 57
  • 171