gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:46:59 25 4
gpt4 key购买 nike

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

代码:

#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 次,它会出现段错误。变量数组也被声明为全局变量。

最佳答案

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

关于c - 如何正确分离共享内存段 - 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43541043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com