strcpy崩溃了程序

时间:2018-05-08 18:23:21

标签: c strcpy

源代码:

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循环中插入第二次时程序崩溃了。具有讽刺意味的是,当我手动操作或在笔记本电脑上运行程序时,它可以工作。我对所有的帮助感到高兴。

1 个答案:

答案 0 :(得分:4)

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

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

这是因为value作为pqueue_insert传递给char*,因此sizeof运算符的编译时评估不会为您分配足够的空间。尝试将分配更改为:

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

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