⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 1.cpp

📁 本程序模拟100块球场的资源分配
💻 CPP
字号:
//内存泄露(原来)
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>

struct TennisGround
{
int num;
char agentName[20];//原来 char * agentName;
};

typedef struct TennisGround TG;

void mallocTG(TG *total);
void freeTG(TG *total);
   




/////////////////////////////////////////////////////////
     int main()
{
    int i;
    int sw;
    TG *total = (TG*)malloc(sizeof(TG)*100);

    for(i=0; i<100; i++)
	{
      (total+i)->num = i; 
      strcpy((total+i)->agentName ," ");
	}

   while(1)
{
    printf("*******Tennis Ground Mallocation******************\n");
    for(i=0; i<100; i++)
	{
       printf("%d(%s) ", (total+i)->num, (total+i)->agentName);
       if((i+1)%5 == 0)
       printf("\n");
	}
	
    printf("\n");
    printf("**************************************************\n");
    printf("Please input your choosen:(1-malloc,2-free,0-break):");

    scanf("%d", &sw);
    if(sw == 1)
        mallocTG(total);
    else if(sw==2)
        freeTG(total);
	else
		break;

}
 delete []total;
   return 0;
}
/////////////////////////////////////////////////////////
	  void mallocTG(TG *total)
{
   int size, start,count = 0;
   char *Name = new char [10];

   printf("Please input your agentName:");
   scanf("%s", Name);

   printf("Please input the size of the TennisGround:");
   scanf("%d", &size);

   printf("Please input the TennisGround number you want to start:");
   scanf("%d", &start);

  while(strcmp((total+start)->agentName, " ")!=0)
   {
     printf("The room is already allocated!!\n");
     printf("Please reinput the TennisGround number you want to start:");
     scanf("%d", &start);
  }
   
   while(strcmp((total+start+size-1)->agentName," ")!=0)
   {
      printf("Please reinput the size of the TennisGround:");
      scanf("%d", &size);
   }
      while(count < size)
	  {
        strcpy((total+start+count)->agentName , Name);
         count++;
	  }
  delete []Name;
}
/////////////////////////////////////////////////////////
	      void freeTG(TG* total)
{
     char *an = (char*)malloc(sizeof(char)*10);
     printf("please input agentName you want to free:");
     scanf("%s", an);
     int count = 0;
     while(count < 100)
	 {
        if(strcmp((total+count)->agentName, an) == 0)

        strcpy((total+count)->agentName , " ");

        count++;
	 }
     delete []an; 
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -