I have a program and in there, I dynamically allocate memory by using malloc; here is the important part:
unsigned int *hours;
unsigned int *minutes;
hours = (unsigned int *) malloc(n * sizeof(*hours));
minutes = (unsigned int *) malloc(n * sizeof(*minutes));
After this, I have a for loop, that loops n times; each time it reads time and stores hours at hours[i] and minutes at minutes[i]; for (i = 0; i < n; i++)
I read n before allocation using :
scanf(%d, &n);
Next, I have function, that takes 3 parameters, it looks like this:
void convertToMinutes(unsigned int *hours[],unsigned int *minutes[],int n)
{
unsigned int i;
for (i = 0; i < n; i++)
{
*minutes[i] =*hours[i]*60 + *minutes[i];
}
}
This is part that causes program to crash. I’m using Dr. Memory to see what happens, here is dump:
Error #1: UNADDRESSABLE ACCESS: reading 0x00000005-0x00000009 4 byte(s)
# 0 convertToMinutes
# 1 main
Note: @0:00:11.408 in thread 1740
Note: instruction: mov (%eax) -> %ecx
As you can see, it tries to read address at 0x00000005, which causes Windows to shut it down.
So before calling this function, I looked at addresses of hours and minutes arrays and here is what I found:
for n = 3
hours base 10948584
hours+1 10948588
hours+2 19848592
minutes base 10948608
minutes+1 10948612
minutes+2 10948616
(Addresses are converted to int)
I’m lost. I have no idea what is wrong. Pointers are new to me (I’ve been using them for few days) and I have no idea why it suddenly tries to read at forbidden address. What am I doing wrong?
This function signature takes arguments that are arrays of
pointerto unsigned intbut your arrays are arrays of
unsigned intnotunsigned int *. Try changing it toor (since array arguments will decay to a pointer anyway) even
The inside the function remove the dereferencing and change to: