如何正确分离共享内存段 - 分段错误

时间:2017-04-21 11:02:27

标签: c memory-management hashtable ipc shared-memory

我正在编写一个创建和使用哈希表并使用共享内存的程序。我的程序有效但有时会导致分段错误。我相信,自从我第一次使用它以来,我没有正确分离共享内存段。 每次使用时我应该分离吗?在此先感谢您的帮助!

代码:

#define SIZE 83000

int indexar = 0;
int shared = 0;

char Entries[SIZE][256];
char st_arr[SIZE][256];


int shmid;
char (*array)[SIZE][50];
int foo = 0;

void put(char *key, char *value ) {


  //item->uniq = uniq;
  int found = 0 ;


  shmid = shmget(123, SIZE * 50, IPC_CREAT | 0666);

  array = shmat(shmid, 0, 0);

  strcpy(st_arr[indexar], key);



  if (foo == 0 ) { /* shared memory initialized once */

    for (int i = 0; i < SIZE; i++)
    {
      strcpy((*array)[i], "0");
    }
    foo = 1;

  }



  for (int i = 0; i < indexar ; i++ ) {

    if (!strcmp(st_arr[i], key)) {

      found = found + 1;

    }
  }


  //get the hash
  unsigned long hashIndex = get_hashed(key, found);

  //move in array until an empty or deleted cell
  while ((strcmp((*array)[hashIndex], "0") && (strcmp((*array)[hashIndex + 1], "0")))) {
    //go to next cell
    hashIndex = hashIndex + 2;

    //wrap around the table
    hashIndex %= SIZE;
  }

  //strcpy(Entries[hashIndex],key);
  //strcpy(Entries[hashIndex+1],value);



  //printf("%d shmid\n",shmid );

  //char (*array)[SIZE][50];
  //shmid = shmget(123, SIZE * 50, IPC_CREAT | 0666); //for shared memory
  //array = shmat(shmid, (void *)0, 0);

  printf("%d\n", hashIndex );
  strcpy((*array)[hashIndex], key);
  strcpy((*array)[hashIndex + 1], value);
  printf("\n[%d] = %s---\n", hashIndex, (*array)[hashIndex] );

  //shmdt((void *) array);

  indexar = indexar + 1;
  shared = shared + 2;
}


///////////////////////////////////////
char *get(char *key) {
  //get the hash
  int uniq = 0;
  unsigned long hashIndex = get_hashed(key, uniq) ;

  shmid = shmget(123, SIZE * 50, IPC_CREAT | 0666);

  array = shmat(shmid, 0, 0);


  //move in array until an empty
  while (strcmp((*array)[hashIndex], "0") && (hashIndex<SIZE))   {


    if (strncmp((*array)[hashIndex] , key, 4) == 0) {
      //printf("%lu \n",hashIndex);
      //shmdt((void *) array);
      return  (*array)[hashIndex + 1];


    }

    //go to next cell
    ++hashIndex;

    //wrap around the table
    hashIndex %= SIZE;

  }

  //printf("%lu \n", hashIndex);
  //shmdt((void *) array);
  return "not found";
}

编辑代码有效,但如果我使用put()函数4-5次则会出现分段错误。变量数组也被声明为全局变量。

1 个答案:

答案 0 :(得分:0)

您应该检查hashIndexhashIndex + (value)限制范围。我的意思是在完整实施时检查hashIndexhashIndex + (value)是否超出限制(例如SIZE