0

I have declared 2 structs: point (which holds 2 doubles) and circle (which holds a point and the radius of the circle, a double).

typedef struct {
    double x;
    double y;   
} point;

typedef struct {
    point m;
    double r;
} circle;

To create a circle I use these 2 functions:

point* read_point() {
    point* p = malloc (sizeof(point));
    printf("\nx middle:");
    scanf("%lf",&p->x);
    printf("\ny middle:");
    scanf("%lf",&p->y);
    return p;
}

circle* read_circle() {
    circle* c = malloc(sizeof(circle));
    point* p = read_point();
    printf("\nradius circle:");
    scanf("%lf",&c->r);
    c->m = *p;
}

In my main I declare an array of circle pointers, add one circle and then try to print out the center point and the radius. (At this point my program crashes.)

circle* array[3];
array[0] = read_circle();
print_circle(array[0]); //Crashes

This is what the print function looks like:

void print_circle(circle* c){
    point p = c->m;
    printf("\n%lf",p.x);
    printf("\n%lf",p.y);
    printf("\n%lf",c->r);
}
3
  • 7
    Craaaaaank up the warnings. -Wall -Wextra on GCC and Clang. Commented Aug 12, 2015 at 15:42
  • 3
    You have a memory leak: You allocate memory for the point, then in read_circle you copy the point structure but never free the memory you allocated for it. Commented Aug 12, 2015 at 15:42
  • a memory leak after point* p = read_point();. Commented Aug 12, 2015 at 15:44

2 Answers 2

4

read_circle isn't returning c (or anything, for that matter).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this was indeed the problem. 2 hours of work for a simple exercise from school and I miss something like that.
0

You might also want to check the return value of malloc().

6 Comments

If I cast using (point*) and (circle*) respectively, is my solution then correct ? (I know I have to free after I use point and circle)
@Agnaroc Don't cast the return value of malloc() What I ment is to check if malloc() failed (i.e. returned NULL)
@Mikrosaft: Good advice, but wouldn't solve the current problem.
@ScottHunter True, but since you already answered it, I didn't feel like I needed to write it again. (It would have made more sense if I commented on his question, but I still can't due to low reputation)
@Mikrosaft in the school examples malloc is always casted. Why shouldn't it be done here ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.