簡體   English   中英

C:Malloc分段錯誤

[英]C: Malloc Segmentation Fault

使用malloc時出現分段錯誤。 當我取消注釋全局COPY&LIST變量並注釋掉malloc和free調用時,程序將按預期運行。

我在濫用malloc還是免費? 如果是這樣,malloc和free的正確用法是什么?

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <time.h>
#include <math.h>

#define MAX_LENGTH 1000000
//int LIST[MAX_LENGTH];
//int COPY[MAX_LENGTH];

/**
 * [main description]
 * Main function reads generated data and then measures run time (in seconds) of each 
 * sorting algorithm. Data is re-shuffled to its original state for each sort.
 * @param  argc
 * @param  argv
 * @return      [returns 0 on successful run]
 * O(n^2)
 */
int main(int argc, char const *argv[])
{
    void read(int*, int*);
    void refresh(int*, int*);
    void selectionSort(long, int*);
    void bubbleSort(long, int*);
    void insertionSort(long, int*);
    time_t start, finish;
    long length = 1000;
    int *LIST = (int*) malloc(length * sizeof(int));
    int *COPY = (int*) malloc(length * sizeof(int));
    read(LIST, COPY);
    for (length = 1000; length <= MAX_LENGTH; length=length+33300) {
        //code omitted
        refresh(LIST, COPY);
        //code omitted
        refresh(LIST, COPY);
        //code omitted
        refresh(LIST, COPY);
        LIST = realloc(LIST, length * sizeof(int));
        COPY = realloc(COPY, length * sizeof(int));
    }
    free(LIST);
    free(COPY);

    return 0;
}
/**
 * [read description]
 * Reads data from stdin, and populates @LIST. 
 * Also populates @COPY, a copy of @LIST. 
 */
void read(int* LIST, int* COPY) {
    long i;
    for (i = 0; i < MAX_LENGTH; i++)
    {
        scanf("%d", &LIST[i]);
        COPY[i] = LIST[i];
    }
}

/**
 * [refresh description]
 * Copies the contents of parameter from into parameter to. 
 */
void refresh(int *LIST, int *COPY) {
    int i;
    for (i = 0; i < MAX_LENGTH; i++) {
        LIST[i] = COPY[i];
    }
}

您正在使用refresh()函數超出范圍。 我正在查看的版本是:

void refresh(int *LIST, int *COPY) {
    int i;
    for (i = 0; i < MAX_LENGTH; i++) {
        LIST[i] = COPY[i];
    }
}

您應該傳遞要復制的項目數,而不要使用MAX_LENGTH

void refresh(int n_items, int *LIST, int *COPY) {
    int i;
    for (i = 0; i < n_items; i++) {
        LIST[i] = COPY[i];
    }
}

在次要的樣式說明上,通常應為宏保留大寫名稱(在POSIX系統上,已知的例外是<stdio.h>FILE<dirent.h> DIR ;它們通常不是宏)。

您的malloc調用中有一個錯誤。 下面的行:

int *LIST=(int*) malloc(sizeof(int*) * length);
int *COPY=(int*) malloc(sizeof(int*) * length);

應該:

int *LIST=(int*) malloc(sizeof(int) * length);
int *COPY=(int*) malloc(sizeof(int) * length);

您正在執行與realloc調用類似的操作。 我不是100%打算使用realloc調用,但是可能應該是這樣的:

LIST = (int*)realloc(LIST, length * sizeof(int));

另外,由於在整個代碼中始終使用int類型,因此您可以定義一些內容來表示單個元素的大小。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM