2017-04-21 161 views
0

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

代码:

#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倍。变量数组也被声明为全局变量。

+0

你可以添加像'st_arr','array'等变量声明吗? – mch

+0

@mch是的,我会编辑 –

+0

'while(strcmp((* array)[hashIndex],“0”)&&(hashIndex mch

回答

0

您应该检查hashIndexhashIndex + (value)的限制范围。我的意思是在你的完整执行检查中,如果hashIndexhashIndex + (value)超出限制(例如SIZE

+0

我会仔细检查它,虽然在我的代码我不分离任何地方的共享内存段(这是我主要关心的)。可以这样做吗? –

+0

如果您分配内存@运行时间,那么你应该让它们在超出范围之后立即释放。 –