gpt4 book ai didi

c - strcpy 使程序崩溃

转载 作者:太空宇宙 更新时间:2023-11-04 06:13:53 25 4
gpt4 key购买 nike

源代码:

priorityqueue_t * pqueue_create() {

priorityqueue_t *pq;

pq = (priorityqueue_t *) malloc(sizeof(priorityqueue_t));

pq->entries = (pqentry_t **) malloc(4 * sizeof(pqentry_t *));
pq->last = 0;
pq->size = 4;
return pq;
}

void pqueue_insert(priorityqueue_t *pq, char* value, float p) {

if (isFull(pq)) {
pq->size *= 2;
pq->entries = realloc(pq->entries, pq->size * sizeof(pqentry_t *));
}


pqentry_t *eintrag = malloc(sizeof(pqentry_t));

eintrag->pqvalue = (char *) malloc(sizeof(value));
eintrag->pqvalue = strcpy(eintrag->pqvalue,value);
//eintrag->pqvalue = value;
eintrag->priotity = p;

//hinten einfügen und einsortieren
pq->entries[pq->last] = eintrag;
pq->last += 1;
sortIn(pq,pq->last - 1);

}

static void sortIn (priorityqueue_t *pq, int pos) {

if (pos >= 1) {
for (int i = pos; i > 0; --i) {
if (pq->entries[i-1]->priotity > pq->entries[i]->priotity) {
pqentry_t *swap = pq->entries[i-1];

pq->entries[i-1] = pq->entries[i];
pq->entries[i] = swap;
}
}
}
}

主要代码:

char* randomString (int size) {

char* str = (char *) malloc((size+1)* sizeof(char));
for (int i = 0; i < size; ++i) {
str[i] = (rand() % 26) + 'A';
}
str[size] = '\0';
return str;
}

int main() {

int i;
char* strings[MAX];
clock_t tic, toc;

srand(time(NULL));

for (i = 0; i < MAX; ++i) {
strings[i] = randomString(8);
}

priorityqueue_t *pq = pqueue_create();

tic = clock();
for (i = 0; i < MAX; i++){
pqueue_insert(pq,strings[i],rand() % 100);
}
toc = clock();

printf("insertion time: %.2f \n", (float) (toc-tic) / CLOCKS_PER_SEC);

tic = clock();
for (i = 0; i < MAX; i++){
pqueue_extractMin(pq);
}
toc = clock();
printf("extraction time: %.2f \n", (float) (toc-tic) / CLOCKS_PER_SEC);

for (i = 0; i < MAX; ++i) {
free(strings[i]);
}
pqueue_destroy(pq);

return 0;
}

我的问题是,当我尝试在 for 循环中第二次插入时,程序崩溃了。具有讽刺意味的是,当我手动执行或在我的笔记本电脑上运行该程序时,它会起作用。我很高兴能得到所有帮助。

最佳答案

您没有在这一行中分配足够的空间:

eintrag->pqvalue = (char *) malloc(sizeof(value));

那是因为 value 被作为 char* 传递到 pqueue_insert 中,所以 sizeof 的编译时评估> 运算符(operator)没有为您分配足够的空间。尝试将分配更改为:

eintrag->pqvalue = malloc(1 + strlen(value));

请注意,C 规范定义了 char 的大小,即 1 个字节,因此您在这里不需要 sizeof(char)。

关于c - strcpy 使程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50240005/

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