问题
It should sort with merge. There are two functions the merge and the sort merge. Some not known functions (read array from file and print array) are totally functional in an input file.
Valgrind show me that the failure is at the allocation from array2 and when it read and write at the 3rd while-loop in void merge.
void merge(int* array, int start, int middle, int end) {
int size = end - start + 1;
int *array2 = malloc(size*sizeof(array2));
int k = start;
int m = middle + 1;
int i = 0;
int j = 0;
while ( k <= middle && m <= end ) {
if ( array[k] <= array[m] ) {
array2[i] = array[k];
k++;
}
else {
array2[i] = array[m];
m++;
}
i++;
}
while ( k <= middle ) {
array2[i] = array[k];
k++;
i++;
}
while ( m <= end ) {
array2[i] = array[k];
k++;
i++;
}
while ( j < i ) {
array[ start + j -1 ] = array2[j];
j++;
}
free(array2);
}
void merge_sort(int* array, int first, int last) {
int middle;
if ( first < last ) {
middle = ((first+last) / 2);
merge_sort (array, first, middle);
merge_sort (array, middle + 1, last);
merge (array, first, middle, last);
}
}
int main (int argc, char *argv[])
{
if (argc!=3) {
printf ("usage: %s <maximale anzahl> <dateipfad>\n", argv[0]);
exit(2);
}
char *filename = argv[2];
int *array;
int size = atoi(argv[1]);
array = malloc(size*sizeof(array));
int len = read_array_from_file(array, atoi(argv[1]), filename);
printf("Eingabe:\n");
print_array(array, len);
merge_sort(array, array[0], len);
printf("Sortiert:\n");
print_array(array, len);
free(array);
return 0;
}
回答1:
At least this is wrong:
int *array2 = malloc(size*sizeof(array2));
I think you mean:
int *array2 = malloc(size * sizeof(*array2));
You want to allocate size times the size of each entry, not the size of the array pointer.
But (on a 64-bit machine) this will actually make your array half the number of bytes, causing your overrun to happen sooner. You have a logic error that you need to figure out by stepping through your code with a debugger.
来源:https://stackoverflow.com/questions/41591621/ive-got-a-segmentation-fault-but-i-dont-find-oo