1

I have a BST structure:

struct bst {
    int *data;
    int max;
};  

And I have a function to create a bst initially:

struct bst *create_bst(int max) {
    struct bst *b;
    b->data = malloc(pow(2, max) * sizeof(int));

    return b;
}

But I'm getting error at the line where I'm allocating memory to data.
Am I doing something wrong?

Choice
  • 85
  • 5

1 Answers1

3

You are not allocating data for the struct itself, just one of its members. This should help:

struct bst *create_bst(int max) {
    struct bst *b;
    if ((b = calloc((size_t)1, sizeof(struct bst))) == NULL) {
        printf("Allocation error\n");
        return NULL;
    }
    if ((b->data = calloc((size_t)1<<max, sizeof(int))) == NULL) {
        printf("Allocation error\n");
        free(b);
        return NULL;
    }

    return b;
}

Later on in some other part of your code, you'll need to clean this memory up. ie: free(b->data); free(b).

Also, remember that pow doesn't work quite how you think it does. You could get something like pow(5,2) == 24.999999..., and when you assign this value to an integer variable, it gets truncated to 24. Never mix and match int and float logic unless you know exactly what you're doing.

Community
  • 1
  • 1
Cloud
  • 18,753
  • 15
  • 79
  • 153