kelahcim
kelahcim

Reputation: 51

abort trap - something is wrong with my code

I am developing linked list in C++. I have issue while using delete.

I read number of elements from program arguments. I can create them. I can list them. When I use delete, code doesn't work.

Do I have to use delete at all?

#include <iostream>
#include <sstream>

struct element {
  int value;
  element *next;
};

int main(int argc, char **argv) {

  int num;
  std::stringstream ss;

  if (argc >= 2) {
    std::cout << argv[0] << std::endl;
    ss << argv[1];
    ss >> num;
    std::cout << "You want: " << num << " numbers" << std::endl;
  } else {
    std::cout << "Error" << std::endl;
  }

  element *first = NULL;
  element *current = NULL;


  // creating
  for(int i=0; i<num; i++) {
    element *elem = new element();
    if( first == NULL ) {
      first = elem;
    }

    elem -> value = i;
    elem -> next = NULL;

    if( current == NULL ) {
      current = elem;
    } else {
      current -> next = elem;
      current = elem;
    }
  }

  // printing
  current = first;
  while( current ) {
    std::cout << "value: " << current -> value << std::endl;
    current = current -> next;
  }

  // removing
  current = first;
  while( current ) {
    delete current;
    current = current -> next;
  }

  delete first;

}

What I want is to print all elements. I know that each new should be accompanied by delete, but something is wrong in my code.

Upvotes: 1

Views: 81

Answers (1)

kelahcim
kelahcim

Reputation: 51

I have fixed my code based on @Yksisarvinen comment. It works now. Thanks!

#include <iostream>
#include <sstream>

struct element {
  int value;
  element *next;
};

int main(int argc, char **argv) {

  int num;
  std::stringstream ss;

  if (argc >= 2) {
    std::cout << argv[0] << std::endl;
    ss << argv[1];
    ss >> num;
    std::cout << "You want: " << num << " numbers" << std::endl;
  } else {
    std::cout << "Error" << std::endl;
  }

  element *first = NULL;
  element *current = NULL;


  // creating
  for(int i=0; i<num; i++) {
    element *elem = new element();
    elem -> value = i;
    elem -> next = NULL;

    if( current == NULL ) {
      first = elem;
      current = elem;
    } else {
      current -> next = elem;
      current = elem;
    }
  }

  // printing
  current = first;
  while( current ) {
    std::cout << "value: " << current -> value << std::endl;
    current = current -> next;
  }

  // removing
  current = first;
  while( current ) {
    element *to_remove = current;
    current = current -> next;
    delete to_remove;
  }
}

Upvotes: 1

Related Questions