-1

I have a struct defined as following:

struct Complex {    
double _real;   
double _img; 
};

I am trying to create a function that returns a pointer to a new complex number based on a c-string input. I begin doing so by trying to create a struct, based on what I've seen on other stackoverflow questions:

 struct Complex * newComplex = (struct Complex*)malloc(sizeof(struct Complex));

Sadly, the code crushes at runtime, saying:

    0 [main] complex 14380 cyg
 trace to complex.exe.stackdump

I also tried running the following, resulting with the same error:

struct Complex * newComplex;
newComplex = (struct Complex*) malloc(sizeof(struct Complex));

When I tried debugging this piece of code, I broke it to parts, coming up with the following code, which seems to work properly:

 struct Complex * newComplex = (struct Complex*)malloc(sizeof(struct Complex));
 void *temp = malloc(sizeof(struct Complex));
 newComplex = (struct Complex*) temp;

I would love to have an explanation to this behaviour.

avneraggy
  • 45
  • 4

1 Answers1

0

Your initial code looks good, the problem must be elsewhere.

// test.c
#include <stdlib.h>
#include <stdio.h>

struct Complex {
    double _real;
    double _img;
};

int main() {
    struct Complex * newComplex = malloc(sizeof(struct Complex));

    newComplex->_real = 0;
    newComplex->_img = 1.0;

    printf("(%f %f)\n", newComplex->_real, newComplex->_img);
    free(newComplex);
    return 0;
}

gcc -Wall test.c ; ./a.out Produces:

(0.000000 1.000000)
Nicolas Defranoux
  • 2,646
  • 1
  • 10
  • 13