C:Malloc分段错误

时间:2014-09-15 17:34:46

标签: c malloc free

使用malloc时出现分段错误。当我取消注释全球COPY& LIST变量并注释掉malloc&免费通话,该程序按预期运行。

我是否误用malloc或免费? 如果是这样,malloc&的正确用法是什么?自由?

#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];
    }
}

2 个答案:

答案 0 :(得分:3)

您正在使用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];
    }
}

在次要样式注释中,您通常应为大写保留大写的大写字母(来自FILE的{​​{1}}和来自<stdio.h>的{​​{1}}的已知例外情况系统;它们通常不是宏)。

答案 1 :(得分:2)

您的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电话类似的操作。我对realloc来电的意图不是100%,但它可能应该是这样的:

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

或者,您可以定义一些内容来表示单个元素的大小,因为您始终在整个代码中使用int类型。