linked list작성중입니다.

junteken의 이미지

linked list를 작성중입니다. 파일로 부터 값을 읽어들여서 링크드 리스트를
구성하고 다시 파일로 쓰는 작업인 아주 간단한 프로그램 입니다.
그런데 제 상식으로는 이상한 현상이 발생하는 군요...

일단 링크를 구성하는 각 노드의 class는 다음과 같습니다.

#ifndef SCORENODE_H
#define SCORENODE_H

#include <iostream>

using namespace std;

struct SCORETAG
{
	char name[10];
	int score;
};

class CScoreNode
{
	friend class CScoreList;

public:
	char *getName();
	int getScore();
	CScoreNode();
	CScoreNode(SCORETAG src);
	virtual ~CScoreNode();

private:
	SCORETAG s;
	CScoreNode *nextPtr;
};

#endif

//////////////구현부///////////////////////

#include "ScoreNode.h"

CScoreNode::CScoreNode()
{
	//값을 default로 초기화 하는 부분이 들어가 주어야 한다. 
	memset(s.name, 0x00, sizeof(s.name));
	s.score=0;
	this->nextPtr=NULL;
}

CScoreNode::CScoreNode(SCORETAG src)
{
	//src로 부터 받은 값으로 초기화 하는 부분이 들어가 주어야 한다. 
	strncpy(s.name, src.name, strlen(s.name));
	s.score= src.score;

}

char *CScoreNode::getName()
{
	//s의 멤버 변수의 이름을 리턴해주면 된다. 
	return s.name;

}

int CScoreNode::getScore()
{
	return s.score;

}

CScoreNode::~CScoreNode()
{
	this->nextPtr= NULL;

}

그리고 링크드 리스트class 는 다음과 같습니다.


#ifndef SCORELIST_H
#define SCORELIST_H

#include "ScoreNode.h"

class CScoreList{
public:

	CScoreList();
	virtual ~CScoreList();
	void insertAtFront(CScoreNode &);
	void insertAtBack(CScoreNode &);
	void removeFromFront();
	void removeFromBack();
	void print() ;
private:
	CScoreNode *firstPtr;
	CScoreNode *lastPtr;
	CScoreNode *getNewNode();

};

#endif


////////////////////////구현부


#include "ScoreList.h"

CScoreList::CScoreList()
{
	this->firstPtr=NULL;
	this->lastPtr=NULL;
	

}

void CScoreList::insertAtBack( CScoreNode &in)
{
	
	//먼저 firstPtr이 가리키고 있는 ptr을 in에다가 저장해주어야 한다. 
	if(lastPtr==NULL)
		lastPtr=&in;

	if( firstPtr==NULL)
		firstPtr=&in;
	else{
		in.nextPtr= firstPtr;
		firstPtr=&in;
	}
}

void CScoreList::insertAtFront( CScoreNode &in)
{
	//last pointer부분을 조작한다. 
	
	if(firstPtr==NULL)
		firstPtr=&in;
	if(lastPtr==NULL)
		lastPtr= &in;
	else
		lastPtr->nextPtr= &in;

}

void CScoreList::removeFromBack()
{
	//first pointer부분을 조작한다. 

	CScoreNode *temp;

	temp=firstPtr;

	firstPtr= firstPtr->nextPtr;

	//delete temp;
}

void CScoreList::removeFromFront()
{
	//last pointer부분을 조작한다. 

	//last pointer가 맨 마지막 노드의 바로 전에 놈을 가르켜야 하므로
	CScoreNode *temp= firstPtr;

	while(temp->nextPtr != lastPtr)
		temp= temp->nextPtr;

	//delete lastPtr;

	lastPtr=temp;
}

CScoreNode *CScoreList::getNewNode()
{
	return new CScoreNode();
}

void CScoreList::print() 
{
	CScoreNode *temp= firstPtr;

	while(temp->nextPtr !=NULL){
		cout<<"NAME= "<<temp->getName()<<"  SCORE= "<<temp->getScore()<<endl;	
		temp=temp->nextPtr;
	}
}

CScoreList::~CScoreList()
{

}

//테스트할 main부분입니다.

#include "ScoreList.h"
#include "ScoreNode.h"
#include <fstream>

using std::ofstream;
using std::ifstream;

int main(void)
{
	char name[10];
	int score;
	SCORETAG tag;
	CScoreList list;
	//파일 객체를 초기화 시킨다. 
	ifstream in("input.txt", ios::in);
	ofstream out("output.txt", ios::out);

	if( !in){
		cerr<<" File could not be opened"<<endl;
		exit(1);
	}

	if( !out){
		cerr<<" File could not be opened"<<endl;
		exit(1);
	}

	//파일을 읽어 들인다. 

	while(in>>name>>score){		
	
		strncpy(tag.name, name, strlen(name)+1);
		tag.score= score;

		CScoreNode *temp= new CScoreNode(tag);

		list.insertAtBack(*temp);
	}

	cout<<"After Reading from input.txt file!!!"<<endl;
	list.print();
	//노드를 지운다. 
	list.removeFromBack();
	list.removeFromFront();

	cout<<"After removing from list!!!"<<endl;
	list.print();

	//output.txt로 파일을 쓴다. 
	

	return 0;

}

위에 코드를 보시면 위에 main함수안에 removeFromBack이 호출되면서
removeFromBack함수안에 "delete temp"이 코드에서 run time오류가
발생합니다. 메모리접근 문제인거 같은데요....제생각에는 알맞게 삭제 해주고
있다고 생각하고있습니다만...뭔가 제가 모르는점이 있는가요?
왜 메모리 오류가 날까요??

긴문장 보아줏서 감사드립니다.
그럼 모두들 행복하세요~~

doldori의 이미지

CScoreNode::CScoreNode(SCORETAG src) 
{ 
   strncpy(s.name, src.name, strlen(s.name)); // error. strlen(src.name)+1 이어야 함
   s.score= src.score; 
} 

이렇게 멤버별로 복사하는 식으로 하지 말고 그냥 구조체 자체로 초기화하는 것이
좋습니다. 생성자의 인자도 참조형으로 넘기고요.

CScoreNode::CScoreNode(const SCORETAG& src) : s(src), nextPtr(0) { }

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.