목록에 대한 자체 제작 프로그램을 만들려고했습니다. 그래서 저는 목록을 만들고, 새 노드를 추가하고, 표시하고, 목록에있는 모든 기존 노드를 삭제하는 것과 같은 기본적인 것들을 만들었습니다.
그러나 목록에 27 개 이상의 요소를 넣으면 메모리를 해제하는 동안 분할 오류 오류가 발생합니다. 덧붙여서 26 개 이하로 추가하면 잘 작동합니다. 스택이 넘쳐나거나 그런 것 같으면 정말 모르겠어요.
추신은 내가 자전거를 개발하고 있다고 말하지 않습니다. 이런 식으로 먼저 스스로 무언가를 만들고, 더 잘 이해합니다.)
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
typedef struct node{
struct node * next;
int value;
} node;
int addNode(int position,int value, node ** head,int * size){
int i = 2;
node * curNode = *head;
if(position > *size) return;
while(i <= *size){
if(position == 1){
node * adress = *head;
*head = (node*) malloc(sizeof(node*));
(*head)->next = adress;
(*head)->value = value;
break;
}
else if(i == position){
node * adress = curNode->next;
curNode->next = (node*) malloc(sizeof(node*));
curNode = curNode->next;
curNode->next = adress;
curNode->value = value;
break;
}
else{
curNode = curNode->next;
++i;
}
}
++(*size);
return;
}
void showList(node * head, int size){
int i; node * currentNode = head;
for(i = 0; i < size; ++i){
printf(" %d , next adress: %p |\n", currentNode->value, currentNode->next);
currentNode = currentNode->next;
}
printf("\n");
}
void cleanList(node * head, int size){
int i;
node * curNode = head; node * nextToDelete = NULL;
for(i = 0; i < size; ++i){
nextToDelete = curNode->next;
free(curNode);
curNode = nextToDelete;
}
}
int main() {
node * head = (node*) malloc(sizeof(node*)); //saving head adress to know where the list starts
head->value = 1; //set head value as "1"
int i, size;
node * currentNode = head; //pointer which points to a current node
for(i = 0; i < 5; ++i){
node * adress = (node*) malloc(sizeof(node*)); //variable which saves new node`s adress
currentNode->next = adress; //set this new nod`s adress to previous node`s "next" parametr
currentNode = adress; //set new node`s adress to a current node
currentNode->value = i+2; ///set value for this node
}
size = 6;
addNode(2, 15, &head, &size);
showList(head, size);
showList(head, size);
cleanList(head, size);
return 0;
}
메모리를 잘못 할당하고 있습니다.
다음 줄에 유의하십시오.
*head = (node*) malloc(sizeof(node*));
과
curNode->next = (node*) malloc(sizeof(node*));
struct node
실제 구조체 대신 포인터에 메모리를 할당 하고 있습니다. 함수에
주목하십시오 sizeof
-잘못된 매개 변수를 전달했습니다!
구조에는 int
및 포인터가 있습니다. 그것들은 보통 같은 크기입니다.
하지만 포인터에 메모리 만 할당하므로 구조의 절반 만 할당합니다.
이로 인해 free
어느 시점에서 잘못된 주소 로 전화를 겁니다 . 프로그램이 free
작동 중에 만 충돌 한 것은 기적 입니다. 훨씬 빨리 충돌 했어야합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다