處理動態陣列上的邊界誤差

[英]Address boundary error on dynamic array


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

我只是從一種解釋語言背景的C開始,我在理解為什么它不能工作上有困難。

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

我有一個Dynamic_Array struct (http://pastebin.com/h4k7Sk3U)和一個任務結構體(http://pastebin.com/evs4TEQA)。

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

在創建具有初始大小的Dynamic_Array實例時:

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

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

我跟蹤了gdb的錯誤,gdb顯示它起源於dynamic_array。

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.

我哪里做錯了?我將初始大小與任務結構體的大小相乘,任務結構體應該有足夠的內存。

1 个解决方案

#1


6  

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

在開始創建它的成員之前,從來沒有分配過a本身。

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

在你初始化它之前,a指向一些你不應該接觸的隨機內存位置。

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;
}

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/09/04/7300f63f72fff202e66bacfefb2feec2.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com