C malloc - struct - SIGFAULT - wie Speicher zuweisen?

jkallup

Erfahrenes Mitglied
Hallo Gemeinde,

habe folgenden Code.
Möchte gerne Speicher zuweisen, bekomme aber SIGFAULT.
ab der Stelle im Code (makiert).
Wenn jemand helfen kann, das Speicher zugeordnet werden
kann, dann bitte hier schreiben.

Danke

Code:
typedef struct {
    int type;
    int mode;
    float value;
    QString text;
} conNodeType;

typedef struct {
    nodeEnum oper;
    int nops;
	struct nodeType ** op;
} oprNodeType;

typedef struct nodeType {
    nodeEnum type;

	union {
		conNodeType con;
		oprNodeType opr;
	};
} nodeType;

struct nodeType * con_expr(struct nodeType * state, float val)
{
	if (state != nullptr) {
		struct nodeType * pv1 = (struct nodeType*) malloc(sizeof(struct nodeType));
		struct nodeType * pv2 = (struct nodeType*) malloc(sizeof(struct nodeType));

		state->opr.op = (struct nodeType*) malloc(4*sizeof(struct nodeType)); // <<---------- huer

		pv1->type        = state->type;
		pv1->con.value   = state->con.value;
		state->opr.op[0] = pv1;

		pv2->type        = typeExpr;
		pv2->con.value   = val;
		state->opr.op[1] = pv2;
	}
	else {
		yyerror("memory allocation error.");
		return nullptr;
	}

    return state;
}
 
Hi

a) malloc ist hier fehl am Platz (weil QString usw.usw.).
Es muss new sein.
Oder gleich Vektoren usw.usw.

b) schalt die Compilerwarnungen ein und verbesser sie.
Alle.
Zumindest einige falsche Typen hast du nämlich drin.
 
Zudem empfehle ich dir die Namensgebung zu überdenken:

conNodeType
oprNodeType

Ich denke für den Leser ist interessanter was "con" und "opr" sind als "NodeType". Klar ist es gut zu wissen, dass die wohl etwas mit nodeType zu tun haben, aber wenn du etwas abkürzt im Namen dann lieber den Teil.

Unnamed unions/structs sind übrigens eine non-standard Erweiterung, offiziell also eigentlich ein Syntaxfehler.
 
Zurück