user3562409
user3562409

Reputation: 1

EXC_BAD_ACCESS error in C

I'm running a simple program in C:

#include <stdio.h>
#include <stdlib.h>

void qr_symmetric (double *a, int n, double *b);
void identityshift(double *a, double *b, int size);



int main ()
 {
     double *a = malloc(10);
     double *b = malloc(10);
     for (int i = 0; i<9; i++)
     {
         a[i]=2;
     }
     qr_symmetric(a, 3, b);
     for (int i = 0; i<9; i++)
     {
         printf("%f\n", b[i]);
     }
 }

void qr_symmetric (double *a, int n, double *b)
{
    b = malloc(10);
    for (int i = 0; i<(n*n); i++)
    {
        b[i]=a[i];
        printf("%f\n", a[i]);
    }
    identityshift(a, b, n);
}

void identityshift(double *a, double *b, int size)
{
    int num = a[0];
    for (int i=0; i<(size*size); i=(i+size))
    {
        b[i]=b[i]+num;
    }
 }

Whenever I run the code, however, I get an EXC_BAD_ACCESS (code=EXC_I386_GPFLT) error on this line:

 printf("%f\n", a[i]);

after it prints a[i] twice.

It seems that no matter what I substitute in for a[i], even a constant like 2.0, I keep getting an EXC_BAD_ACCESS error with different codes each time. What am I doing wrong?

Upvotes: 0

Views: 227

Answers (2)

Tofandel
Tofandel

Reputation: 3555

You have to multiply the size to allocate by the size in bits of the stored type So it would be

double *b = malloc(10*sizeof(double));

And you have a memory leak because your allocating twice b..

So you have to test if b is null before doing a malloc on it in your qr_symmetric function

void qr_symmetric (double *a, int n, double *b)
{
    if (b==NULL) b = malloc(10*sizeof(double));
    else b = realloc(b, 10*sizeof(double));
    //...
}

or simply remove the first malloc in that case..

Upvotes: 1

Anycorn
Anycorn

Reputation: 51435

malloc allocates memory in bytes, you need to multiply number of elements by sizeof of a single elements, eg sizeof(double)

Upvotes: 3

Related Questions