从结构中释放内存

时间:2013-12-18 02:50:04

标签: c memory-management

我基本上试图从具有用户输入数据的结构中取消分配内存,因此目标是擦除数据,以便可以将新的数据集重新输入到结构中。

这是结构

 struct packet{
    int source;
    int destination;
    int type;               // Varibles for the structure
    int port;
    char data[50];
    char * filename;
};

指向结构的指针

struct packet s[50];         //Array for structure input
struct packet *p_s;
p_s = malloc(sizeof(struct packet));

用户输入数据的代码被添加到结构中的变量

printf("\n****Adding a packet*****\n");
printf("Where is the packet from?\n");
scanf("%i", &s[NetworkPacket].source);
printf("Where is the packet going?\n");
scanf("%i", &s[NetworkPacket].destination);
printf("What type is the packet?\n");
scanf("%i", &s[NetworkPacket].type);  // collecting the data of the packet inputted by the user
printf("What is the packet's port?\n");
scanf("%i", &s[NetworkPacket].port);
printf("Enter up to 50 characters of data.\n");
scanf("%s", s[NetworkPacket].data);

这是我查看结构数据的方式

        printf("\n%i\nSource: %d", ii, s[ii].source);
        printf("\nDestination: %d", s[ii].destination );
        printf("\nType : %d", s[ii].type);// if statement giving the limit of 50 packets allowed to be added
        printf("\nPort : %d", s[ii].port);
        printf("\nData: %s\n---\n", s[ii].data);

最后代码我想帮助它从上面删除用户输入的数据集,这样就可以添加一个新的集合。

system("cls");
free(p_s);
printf("All the data entered has been cleared. Press any key to continue");

2 个答案:

答案 0 :(得分:1)

您只需要free(p_s);。您不能逐个取消分配成员,因为它们也没有逐个分配。

答案 1 :(得分:1)

如果要重新使用先前分配的内存。您可以使用memset将所有已分配的内存填充到'\ 0'。通过这样做,您将重置除char *文件名之外的整个strcuture!这个char *你需要分配和dellocate独立于分配或取消分配父结构。