gpt4 book ai didi

c - 释放嵌套结构的指针时出现段错误

转载 作者:太空宇宙 更新时间:2023-11-04 08:28:57 33 4
gpt4 key购买 nike

这是我的代码:

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

#define NAMESIZE 20
#define LINESIZE 1024

typedef struct name name;
struct name
{
char last[NAMESIZE]; /* last name */
char first[NAMESIZE]; /* first name*/
};

typedef struct record record;
struct record
{
name name;
int score;
};

typedef struct record_list record_list;
struct record_list
{
record *data; /* the dynamic array of records */
size_t nalloc; /* number of records allocated */
size_t nused; /* number of records in use */
};

void list_init(record_list *list)
{
list -> data = 0;
list -> nalloc = 0;
list -> nused = 0;
}

int list_insert(record_list *list, const record *rec)
{
size_t newSize;
record *tmp;

if(list -> nalloc == list -> nused)
{
if(list -> nalloc == 0)
{
newSize = 1;
}
else
{
newSize = 2 * list -> nalloc;
}

tmp = realloc(list -> data, newSize * sizeof(record));

if(tmp == 0)
{
return 0;
}

list -> data = tmp;
list -> nalloc = newSize;
}

list -> data[list -> nused++] = *rec;

return 1;
}

void list_destroy(record_list *list)
{
printf("Attempting Deletion");
free(list->data);
free(list->nalloc);
free(list->nused);

list -> data = 0;
list -> nalloc = 0;
list -> nused = 0;
}

int main(void){
record_list list;
record *r;
name n;

int score;

char input[NAMESIZE];
char name[NAMESIZE];
char lname[NAMESIZE];


list_init(&list);
while(input != NULL) {
printf("Please enter a value for Name: ");
scanf("%s", input);
strcpy(input, name);
printf("Enter last name: ");
scanf("%s", input);
strcpy(input, lname);
printf("Enter score: ");
scanf("%d", &score);

r=(record*)malloc(sizeof(record));
if(r == NULL){
printf("There isn't enough memory.\n");
}
strcpy(n.first, name);
strcpy(n.last, lname);
r -> name = n;
list_insert(&list, r);
printf("\n");
printf("Choose next action:\n");
printf("\tTo add more type \"add\";\n");
printf("\tTo delete all records type \"del\";\n");
scanf("%s", input);
if(strcmp(input, "del") == 0){
list_destroy(&list);
printf("Deleted");
break;
}
}


return 1;
}

我正在做一个小的实验练习,我们制作一个结构,填充它并在用户需要时清除它。昨天一切正常,但今天我似乎要么没有保存它,要么破坏了一些东西,因为我遇到了很多错误。这是我收到的错误示例:

基本上当我调用一个方法时

void list_destroy(record_list *list);

它在到达第一个打印语句之前崩溃,这意味着我在方法调用方面做错了。

问题总结:什么可能导致段错误(我在哪里访问了不正确的内存)或者我还可以如何在不使用 free 的情况下清除我的结构内存?

非常感谢。

最佳答案

这应该说明您的问题是什么:

code.c: In function 'list_destroy':
code.c:74: warning: passing argument 1 of 'free' makes pointer from integer without a cast
code.c:75: warning: passing argument 1 of 'free' makes pointer from integer without a cast

您正在尝试释放 int 字段。您不能释放它们,因为它们不是指向内存块的指针。

因此,删除这些代码行:

free(list->nalloc);
free(list->nused);

关于c - 释放嵌套结构的指针时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29242829/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com