Noel
Noel

Reputation: 2091

C Malloc to a Pointer Through Function Call Causes Bus Error

Due to my feeble understanding of allocating type memory to pointers, the following causes a bus error on the call to barrier_create ("hi" is never printed).

typedef struct barrier barrier_t;
typedef struct barrier *barrier_p;

barrier_p test_barrier_p;

int main(int argc, char *argv[]) {
    barrier_create(*test_barrier_p);
}

int barrier_create(barrier_p *barrier_pointer) {
printf("hi\n");
    barrier_p old_barrier, new_barrier;
    int count;
    old_barrier = (barrier_p) *barrier_pointer;
    new_barrier = (barrier_p) malloc(sizeof(*new_barrier));
    count = pthread_mutex_init(&new_barrier->lock, NULL);
    new_barrier->is_valid = VALID_BARRIER;
    new_barrier->counter = 0;
    new_barrier->release_flag = 0;
    *barrier_pointer = new_barrier;
    return HAPPY_HAPPY_JOY_JOY;
}

What am I missing or mis-typing?

Upvotes: 0

Views: 2450

Answers (4)

Jason Coco
Jason Coco

Reputation: 78393

You're dereferencing a bad pointer in your main function. To get the address of the variable, you use the address & operator, not the dereferencing * operator. Rewrite main as:

barrier_create(&test_barrier_p);

Upvotes: 7

dubnde
dubnde

Reputation: 4441

The function int barrier_create(barrier_p *barrier_pointer) takes a pointer as an argument. However, you a passing in an actual barrier_p in your main since you dereference it - barrier_create(*test_barrier_p). I think you should be passing the address like barrier_create(&test_barrier_p)

Upvotes: 0

Kim Reece
Kim Reece

Reputation: 1280

barrier_create(*test_barrier_p);

Since barrier_create takes address of a barrier_p, this should be &test_barrier_p, not *test_barrier_p.

printf("hi\n");

Inaccurate test of code reachability because stdout is likely buffered; I'd recommend fprintf(stderr, "hi\n"); instead.

new_barrier = (barrier_p) malloc(sizeof(*new_barrier));

I'd say sizeof(barrier_t). Again a * in an odd place, the _p notation may not be helping your type manipulation clarity.

For pedanticism, I would check the return value of malloc. I see little point in keeping the old value unless to recover in some way from a malloc error.

What is the purpose of count?

Upvotes: 7

paxdiablo
paxdiablo

Reputation: 882028

The test_barrier_p variable is a pointer to a barrier structure which is never being initialized, so it's set to NULL (since it's at file scope).

You're de-referencing it at the call from main() to barrier_create().

For help beyond that, you'll need to tell us, in English, what you're trying to achieve.

Upvotes: 0

Related Questions