私は、ハッシュテーブルを作成して使用し、共有メモリを使用するプログラムを作成しています。私のプログラムは動作しますが、セグメンテーションフォルトが発生することがあります。私はそれを初めて使用して以来、私は共有メモリセグメントを適切に切り離してはいけないと考えています。 私はそれを使用するたびにセグメントを取り外すべきですか?あなたの助けを前もってありがとう!正しく共有メモリセグメントを切り離す方法 - セグメンテーションフォールト
コード:
#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";
}
編集:コードは動作しますが、私は()関数に4-5回を入れて使用する場合には、セグメンテーションフォールトを与えます。また、可変配列はグローバル変数として宣言されます。
「st_arr」、「array」などの変数の宣言を追加できますか? – mch
@mchはい私は –
'(strcmp((*配列)[hashIndex]、" 0 ")&&(hashIndex 'while((hashIndex
mch