I have this simple bubblesort program that when compiled on macOs works correctly, but when compiled on linux (with gcc), gives a segmentation fault at runtime. I would love to understand why.
#include <stdio.h>
#include "alg_utils.h"
void bubble_sort(int *, int);
int main() {
int array[10] = {5, 10, 77, 1, -2, -61, 18, 14, 57, 7};
bubble_sort(array, 10);
print_array(array, 10);
return 0;
}
void bubble_sort(int *array, int len) {
int i, j;
for (i=0; i < len; i++) {
for (j=0; j < len; j++) {
if (array[j] < array[j-1])
swap(&array[j], &array[j-1]);
}
}
}
On mac:
~/Projects/Algorithms: gcc Bubblesort.c
~/Projects/Algorithms: ./a.out
-2 0 1 5 7 10 14 18 57 77%
On linux:
root#f95445bcd4e7:~/algos$ gcc Bubblesort.c
root#f95445bcd4e7:~/algos$ ./a.out
Segmentation fault
The alg_utils.h only has the definition of the swap() and print_array() functions. Nothing crazy.
void print_array(int *, int);
void swap(int *, int *);
void swap(int *a, int *b) {
int temp = *b;
*b = *a;
*a = temp;
}
void print_array(int *array, int len) {
int i;
for (i=0; i < len; i++) {
printf("%4d", array[i]);
}
}
When I change the main() with main(int argc, char *argv[]) it works on linux too.
Linux (with main(int argc, char *argv[])
root#f95445bcd4e7:~/algos$ gcc Bubblesort.c
root#f95445bcd4e7:~/algos$ ./a.out
-2 1 1 5 7 10 14 18 57 77
So I thought: linux doesn't like main with no params...but then a simple hello world like this runs just fine.
#include <stdio.h>
int main() {
printf("hello world\n");
return 0;
}
So, i'm confused. What is it? Maybe alg_utils? Maybe different c implementations? I've tried compiling with -std=c99 (and other combinations) to no avail.
Does somebody have any clue? Thank you in advance
array[j-1]
forj=0
? – Eugene Sh.