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?

asked Nov 17, 2014 at 13:29
14
  • You getting an error because you have not allocated memory for b since you defined it as a pointer to a struct bst Commented Nov 17, 2014 at 13:31
  • What is the value of max when the malloc fails? Commented Nov 17, 2014 at 13:31
  • struct bst *b; --> struct bst *b = malloc(sizeof(*b)); Commented Nov 17, 2014 at 13:32
  • @T.V. Do I just add b = malloc(sizeof(struct bst)); ? Commented Nov 17, 2014 at 13:34
  • 2
    @T.V. you misunderstand *b. *b is not pointer. Commented Nov 17, 2014 at 13:44

1 Answer 1

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.

answered Nov 17, 2014 at 13:39
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.