-2

I'm new to C programming. I want to make a linked list, so I did, but it doesn't work. After I do that, I made it for a test, but still it gives an error.

malloc: error for object 0xa000000000000000: pointer being realloc'd was not allocated
set a breakpoint in malloc_error_break to debug

How can I reallocate this array?

void Allocate(int **arr,int totalNum, int subNum)
{
    for(int n=0;n<(totalNum+1);n++)
    {
        arr[n] = (int*)realloc(arr[n],(size_t)((subNum+1)*sizeof(int)));
    }
}
int main()
{
    int totalNum = 20;
    int subNum = 5;
    int **arr;
    arr = (int**)malloc((totalNum+1)*sizeof(int*));
    Allocate(arr,totalNum, subNum);

    for(int n=1;n<(totalNum+1);n++)
    {
        for(int s=1;s<(subNum+1);s++)
        {
            arr[n][s] = rand()%5;
            cout<<"arr["<<n<<"]["<<s<<"]: "<<arr[n][s]<<endl;
        }
    }
}
Ahmet Emre Kilinc
  • 5,489
  • 12
  • 30
  • 42
Matt
  • 1
  • I can't begin to understand the question. Linked lists and arrays are different things, if you're unaware – Passer By Nov 21 '17 at 05:52
  • 1
    *I'm newb on C programming.* -- Why did you tag this as `C++`? C++ has `std::list` if you want a douby-linked list, a `std::forward_list` for a singly-linked list, and `std::vector` for dynamic errors. Thus there is no need for coding to look like this. – PaulMcKenzie Nov 21 '17 at 05:54
  • [don't cast malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Barmar Nov 21 '17 at 05:57
  • C is not C++, please make the tag and the question body match. Never ever use malloc or realloc or arrays or raw pointers in C++. – n. m. could be an AI Nov 21 '17 at 06:48

2 Answers2

1

The program crashes because arr[n] is uninitialized when realloc() is invoked.

i do not fully understand why you want to realloc() instead of malloc() in the Allocate() function. but anyway, let's assume realloc() is what you need.

the easiest fix is to initialize arr content.

arr = (int**)calloc((totalNum+1),sizeof(int*));
Gilles Gouaillardet
  • 8,193
  • 11
  • 24
  • 30
0

The first argument to realloc() has to be either NULL or a pointer that was returned earlier by malloc() or realloc(). You passed an array full of uninitialized data to Allocate(), so you're passing uninitialized pointers to realloc() there. You need to initialize them all to NULL first.

arr = malloc((totalNum+1)*sizeof(int*));
for (int i = 0; i < totalNum+1; i++) {
    arr[i] = NULL;
}
Allocate(arr,totalNum, subNum);
Barmar
  • 741,623
  • 53
  • 500
  • 612