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.

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.