I'm writing a function that is giving me the following error:
/bin/sh: line 1: 15039 Bus error: 10 ( test/main.test )
make: *** [test] Error 138
I had to look up what a bus error was, and apparently it's when a function tries to access an address that doesn't exist? I've been looking through this relatively short function and can't see where that's happening.
#include <stddef.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include "../include/array_utils.h"
int array_new_random(int **data, int *n)
{
int i;
srand(time(NULL));
if(*data == 0){
*data = malloc(*n * sizeof(int));
}
for(i = 0; i < n; i++){
*data[i] = rand();
}
return n;
}
And here is the function that calls it.
void test_array_new_random(void)
{
int *buffer = NULL;
int len = 100;
int ret;
t_init();
ret = array_new_random(&buffer, &len);
t_assert(len, ret);
t_assert(100, len);
free(buffer);
t_complete();
}
And here's some of the other functions that have been called. I don't think they are as important because the code seems to be crashing before it gets to them, but I could be wrong.
void t_assert(int expected, int received)
{
if (expected != received) {
snprintf(buffer, sizeof(buffer), "EXPECTED %d, GOT %d.", expected, received);
t_fail_with_err(buffer);
}
return;
}
void t_init()
{
tests_status = PASS;
test_no++;
printf("STARTING TEST %d\n", test_no);
return;
}
void t_complete()
{
if (tests_status == PASS) {
printf("PASSED TEST %d.\n", test_no);
passed++;
}
}
void t_fail_with_err(char *err)
{
fprintf(stderr, "FAILED TEST %d: %s\n", test_no, err);
tests_status = FAIL;
tests_overall_status = FAIL;
return;
}
Because I seem to be writing a function made to pass a test, you probably correctly guessed that this is a homework assignment.
EDIT: So, an issue was that I was using *data[i]
where I should have been using (*data)[i]
. However, I'm now getting this error:
/bin/sh: line 1: 15126 Segmentation fault: 11 ( test/main.test )
make: *** [test] Error 139