P
P
pentagon97142016-05-04 17:55:15
C++ / C#
pentagon9714, 2016-05-04 17:55:15

How to properly allocate memory?

Hello!
I ran into the following problem - this function works fine in debug mode, but when run normally in a release/debug build, it crashes with an unknown error.

void inputToList()
{
  int i = 0;                                
  link current = list_watch;
  while (input[i] != '\0')
  {
    current->data = (char*)malloc(buf*sizeof(char));
    current->datalen = 0;
    while (input[i] != '\n')
    {
      current->data[current->datalen] = input[i];
      current->datalen++;
      if (current->datalen%buf == 0)
      {
        current->data = (char*)realloc(current->data, (buf + current->datalen)*sizeof(char));
      }
      i++;
    }
    current->data[current->datalen] = '\0';
    i++;
    blockscount++;
    if (input[i] != '\0')
    {
      current->next = (link)malloc(sizeof(link));
      current = current->next;
    }
    else
    {
      current->next = NULL;
    }
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Armenian Radio, 2016-05-04
@gbg

At least your variable is not initialized - list_watch.
If it's a global variable, things get a lot worse.
Checking for errors is also missing - add.

P
Peter, 2016-05-04
@petermzg

At you
And if this '\n' is not present, then you passing '\0' take off for a line.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question