0

Hello,

I have observed a data access misaligned error in my code. I am trying to isolate the issue and find reason for its occurrence.

float *mul;

int main(void)
{
   int i;
    mul=(float *)malloc(36000);
    *mul=0;
    for(i=1; i<9000; i++)
    {
        *(mul+i)=*(mul+(i-1))+(1/(float)(72000/2));
        printf("%f\t", *(mul+i));
    }
    free(mul);
    return 0;
}

Please point errors in my code and if possible some rectifications that I could try.

Thank you.

2
Contributors
2
Replies
5
Views
7 Years
Discussion Span
Last Post by katwalatapan
0

> mul=(float *)malloc(36000);
a) why are you casting malloc in a C program? Did you forget to include stdlib.h?
b) who said sizeof(float) was 4 bytes on your machine?
If you want 9000 floats, then say mul = malloc( 9000 * sizeof *mul ); then it doesn't matter how big floats really are.
c) check for success before trying to dereference the memory.

> *(mul+i)=*(mul+(i-1))+(1/(float)(72000/2));
Consider using subscript notation. It means the same to the compiler, but it's easier on the eye mul[i] = mul[i-1]+(1/(float)(72000/2));

0

Thank you for the comments. It helped me a lot in optimising my code.

> mul=(float *)malloc(36000);
a) why are you casting malloc in a C program? Did you forget to include stdlib.h?
b) who said sizeof(float) was 4 bytes on your machine?
If you want 9000 floats, then say mul = malloc( 9000 * sizeof *mul ); then it doesn't matter how big floats really are.
c) check for success before trying to dereference the memory.

> *(mul+i)=*(mul+(i-1))+(1/(float)(72000/2));
Consider using subscript notation. It means the same to the compiler, but it's easier on the eye mul[i] = mul[i-1]+(1/(float)(72000/2));

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.