Hej mam prostą alokację pamięci
int* result_tab = malloc((end + 1) * sizeof(int));
result_tab[0] = 1;
Gdzie zmienna end jest zwykłym intem. Kompilator wyrzuca mi wyjątek "Naruszenie dostępu do zapisu". Ktoś wie o co tutaj chodzi? Dodam tylko że korzystam z kompilatora z Visual Studio.
Cały kod
#include <stdio.h>
void swap(int* tab, int index1, int index2) {
int tmp = tab[index1];
tab[index1] = tab[index2];
tab[index2] = tmp;
}
// Easy sort alghoritms
void dumb_sort(int* tab_to_sort, int size) {
int index = 0;
do {
if (tab_to_sort[index] > tab_to_sort[index + 1]) {
swap(tab_to_sort, index, index + 1);
index = 0;
continue;
}
index++;
} while (index < size - 1);
}
void bubble_sort(int* tab_to_sort, int size) {
int index1, index2;
for (index1 = 0; index1 < size - 1; index1++)
for (index2 = 0; index2 < size - 1; index2++)
if (tab_to_sort[index2] > tab_to_sort[index2 + 1])
swap(tab_to_sort, index2, index2 + 1);
}
void insertion_sort(int* tab_to_sort, int size) {
int index1, index2, tmp;
for (index1 = size - 2; index1 >= 0; index1--)
{
tmp = tab_to_sort[index1];
index2 = index1 + 1;
while ((index2 < size) && (tmp > tab_to_sort[index2]))
{
tab_to_sort[index2 - 1] = tab_to_sort[index2];
index2++;
}
tab_to_sort[index2 - 1] = tmp;
}
}
// Speed sort alghoritms
void quick_sort(int* tab_to_sort, int start, int end) {
int index1, index2, pivot;
index1 = (start + end) / 2;
pivot = tab_to_sort[index1];
tab_to_sort[index1] = tab_to_sort[end];
for (index2 = index1 = start; index1 < end; index1++)
if (tab_to_sort[index1] < pivot)
{
swap(tab_to_sort, index1, index2);
index2++;
}
tab_to_sort[end] = tab_to_sort[index2];
tab_to_sort[index2] = pivot;
if (start < index2 - 1)
quick_sort(tab_to_sort, start, index2 - 1);
else if (index2 + 1 < end)
quick_sort(tab_to_sort, index2 + 1, end);
}
int* merge_sort(int* tab_to_sort, int start, int end) {
int mid, index1, index2, index;
int* result_tab = (int*)malloc((end + 1) * sizeof(int));
result_tab[0] = 1;
mid = (start + end + 1) / 2;
if (mid - start > 1)
merge_sort(tab_to_sort, start, mid - 1);
if (end - mid > 0)
merge_sort(tab_to_sort, mid, end);
index1 = start;
index2 = mid;
for (index = start; index <= end; index++)
result_tab[index] = ((index1 == mid) || ((index2 <= end) && (tab_to_sort[index1] > tab_to_sort[index2]))) ? tab_to_sort[index2++] : tab_to_sort[index1++];
return result_tab;
}
int main()
{
int tab[6] = { 2, 5, 10, 1, 0, 11 };
merge_sort(tab, 0, 5);
for (int i = 0; i < 6; i++) {
printf("%d ", tab[i]);
}
}
Błąd występuje w funkcji merge_sort()