-3

I have an interesting problem after allocating a double-pointer.

int **bucket;
bucket = (int **)malloc(sizeof(int) * 10);

I have created a double-pointer without any problem and I have also created a single pointer.

int *size;
size = (int *)malloc(sizeof(int) * 10);

In the first loop, I allocated each element of bucket, and, second loop, I am assigning zero to every element of size.

for (i = 0; i < 10; i++)
    *(bucket + i) = (int *)malloc(sizeof(int) * 1);
for (i = 0; i < 10; i++)
    size[i] = 0;

When I am doing assign operation to size, It deletes the address of certain elements of the bucket. Here, the screenshots while I am debugging.

In this stage I have not entered the 2nd loop:

enter image description here

This is after I entered the second loop: enter image description here

What can cause this problem? Any thought?

Kaan Taha Köken
  • 933
  • 3
  • 17
  • 37

1 Answers1

3

The problem as I see it is

bucket = (int **)malloc(sizeof(int) * 10);

it should rather be

bucket = malloc (sizeof(*bucket) * 10);  // take the size from the target variable itself

In case, in your platform, sizeof (int*) is less than sizeof(int), you'll end up having memory overrun while accessing bucket, thereby invoking undefined behaviour.

Notes:

  1. No need to cast the return value of malloc() and family.
  2. Better not to use a hard-coded type for size calculation.
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • If I do not use casting in front of the variable, It does not let me compile. Since I started university, I used this convention, I wrote above. they showed like this. That's, why I confused – Kaan Taha Köken Nov 20 '19 at 13:42
  • Thank you for your help – Kaan Taha Köken Nov 20 '19 at 13:43
  • 1
    @KaanTahaKöken: "*If I do not use casting in front of the variable, It does not let me compile.*" you then do not use a standard compliant C compiler, perhaps a C++ compiler? – alk Nov 20 '19 at 13:48