petar.vukmirovic2's blog

By petar.vukmirovic2, 14 years ago, In English

Hi,

Today I submitted my solution to 7B - Memory Manager, and it seemed to be working fine on my home PC, but when I tested it on Codechef judge it gave wrong answer as soon as on test two. I am running Linux Ubuntu if that may be helpful. Here is the code:

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

#define MAX_M 100
#define MAX_COMMAND 15

char memory[MAX_M], id,m;

/*void print_memory()
{
  int i;
  for(i=0;i<m;i++)
    printf("%d ",memory[i]);
}*/

int allocate(int size)
{
  int i,j,tmp_j;
  
 /* if (size==m)
    return 0;*/
  
  for(i=0; i<m-size; i++)
  {
    for(j=i; (j<i+size) && (memory[j] == 0); j++)
      ;
    if (j==i+size)
    {
      id++;
      memset(memory+i,id,size*sizeof(char));
      return id;
    }
  }
  return 0;
}

char erase(int tmp_id)
{
  char found = 0;
  int i;
  
  for(i=0; i<m; i++)
    if(memory[i] == tmp_id)
      {
	found = 1;
	memory[i] = 0;
      }
      
  return found;
}


void defragment()
{
  int i,j;
  for(i=0; i<m; i++)
  {
    if (memory[i] == 0)
    {
      for(j=i+1; j<m; j++)
	if (memory[j] != 0)
	  break;
      
      int tmp_j =j, count = 0;
	
      for(;memory[j];j++,i++)
      {
	count++;
	memory[i] = memory[j];	
      }
      
      for(j=tmp_j;count;j++,count--)
	memory[j] = 0;
    }
  }
}
int main()
{
  char t,command[MAX_COMMAND];
  int number, tmp_id,i,j;
  scanf("%d%d",&t,&m); getchar();
  for(i=0;i<t;i++)
  {
    gets(command);
    if (command[0] == 'a')
    {
      number = atoi(command+5);
      tmp_id = allocate(number);
      
      if (tmp_id == 0)
	puts("NULL");
      else
	printf("%d\n",tmp_id);
    }
    else if (command[0] == 'e')
    {
      number = atoi(command+5);
      if (erase(number) == 0)
	puts("ILLEGAL_ERASE_ARGUMENT");
    }
    else
      defragment();  
   //printf("\nDebug: "); print_memory(); putchar('\n');
  }
}

And here is the test example:

INPUT

6 1 defragment alloc 10 alloc 1 erase -1 erase 1 erase 1

OUTPUT

NULL NULL ILLEGAL_ERASE_ARGUMENT ILLEGAL_ERASE_ARGUMENT ILLEGAL_ERASE_ARGUMENT

Can someone give me some advice here?

Thanks Petar Vukmirovic.

| Write comment?
»
14 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

You are trying to read ints, but pass pointers to char instead:

scanf("%d%d",&t,&m); getchar();

You would get this warning yourself if you added -Wall to your compiler flags.

  • »
    »
    14 years ago, hide # ^ |
    ← Rev. 2  
    Vote: I like it 0 Vote: I do not like it

    Well, that's what I wanted since the size of t and m is less than 127 which is maximum size for signed char. I want the integer value of char not the character :)

    • »
      »
      »
      14 years ago, hide # ^ |
       
      Vote: I like it 0 Vote: I do not like it

      It doesn't work that way, you are invoking undefined behavior. Read the numbers into ints and then work with them.