Ich schreibe ein Programm, das eine Hash-Tabelle erstellt und verwendet und Shared Memory verwendet. Mein Programm funktioniert, aber manchmal verursacht es Segmentierungsfehler. Ich glaube, dass ich Shared-Memory-Segmente nicht ordnungsgemäß trennen, da es das erste Mal ist, dass ich es benutze. Sollte ich das Segment jedes Mal trennen, wenn ich es verwende? Vielen Dank im Voraus für Ihre Hilfe!So lösen Sie freigegebene Speichersegmente ordnungsgemäß - Segmentierungsfehler
Code:
#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";
}
edit:-Code funktioniert, aber es gibt Segmentierungsfehler, wenn i() Funktion 4-5 mal setzen verwenden. Auch das variable Array wird als globale Variable deklariert.
Können Sie die Deklarationen Ihrer Variablen wie 'st_arr',' Array' usw. hinzufügen? – mch
@mch ja ich werde bearbeiten –
'while (strcmp ((Array) [HashIndex]," 0 ") && (HashIndex 'while ((hashIndex
mch