【发布时间】:2014-09-15 17:34:45
【问题描述】:
我在使用 malloc 时遇到分段错误。当我取消注释全局 COPY & LIST 变量并注释掉 malloc 和 free 调用时,程序按预期运行。
我是在误用 malloc 还是 free? 如果是这样,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];
}
}
【问题讨论】:
-
不要在 C 中转换
malloc。如果这应该是 C++,不要使用malloc并避免使用new和delete。 -
如果可用,请使用valgrind
-
这如何与
malloc版本一起编译?refresh函数引用了LIST和COPY,但它们甚至没有全局定义。 -
@python 没关系。
LIST和COPY名称不引用refresh()中的任何内容,无论函数是放在main()之前还是之后。编译器应该对此给出错误;如果不是,那么 OP 发布的代码与他遇到的问题不同。 -
@hesham8 在我发表评论时,要刷新的参数被称为
from和to,但您在函数体中指的是LIST和COPY。该版本永远不会成功编译。此后,您已更新问题以解决此问题。