Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address boundary error on dynamic array

Tags:

c

I'm just starting with C from a interpreted language background, and I'm having problems understanding why this is not working.

I have a Dynamic_Array struct (http://pastebin.com/h4k7Sk3U), and a Task struct (http://pastebin.com/evs4TEQA).

When creating a Dynamic_Array instance with an initial size I get:

“./ctask ” terminated by signal SIGSEGV (Address boundary error)

I tracked the error with gdb, who shows that its originated on dynamic_array.h:16:

Dynamic_Array *dynamic_array_create(size_t initialSize) {
  Dynamic_Array *a;
  a->array = (Task *)malloc(initialSize * sizeof(Task));   // line 16
  a->used = 0;
  a->size = initialSize;
  return a;
}

What am I doing wrong there? I'm multiplying the initial size with the size of the Task struct, which is supposed to be enough memory for them.

like image 927
jviotti Avatar asked Jun 04 '26 14:06

jviotti


1 Answers

You never allocated a itself, before you started creating its members.

Until you initialize it, a is pointing to some random memory location that you shouldn't be touching.

Dynamic_Array *dynamic_array_create(size_t initialSize) {
  Dynamic_Array *a = malloc(sizeof(Dynamic_Array));  // create 'a' first

  a->array = (Task *)malloc(initialSize * sizeof(Task));
  a->used = 0;
  a->size = initialSize;
  return a;
}
like image 88
Paul Roub Avatar answered Jun 06 '26 04:06

Paul Roub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!