0

I have a structure which is composed of a char* and many attributes.

I can't print my char* as a string, it just crashes.

Here is my code :

int main() {
    sommet_t* sommet = creerSommet("rouge", 5, NULL);
    printf("Couleur : %s", sommet->couleur);
    return 0;
}

And my sommet.c :

sommet_t* creerSommet(char* couleur, int distance, sommet_t* pere) {
    sommet_t* sommet =  malloc(sizeof(sommet_t));
    sommet->distance = distance;
    sommet->couleur = (char*)malloc((strlen(couleur)+1) * sizeof(char));
    strcpy(sommet->couleur,couleur);
    sommet->pere = pere;
}

I absolutely don't know what's wrong in it.

Edit : sommet.h

#ifndef __SOMMET_H__
#define __SOMMET_H__

typedef struct sommet_type {
    char *couleur;
    int distance;
    struct sommet_type *pere;
} sommet_t;

sommet_t* creerSommet(char*, int, sommet_t*);

#endif
alinsoar
  • 15,386
  • 4
  • 57
  • 74

2 Answers2

3

You should return the object from the function creerSommet

sommet_t* creerSommet(char* couleur, int distance, sommet_t* pere) {
    sommet_t* sommet =  malloc(sizeof(sommet_t));
    sommet->distance = distance;
    sommet->couleur = (char*)malloc((strlen(couleur)+1) * sizeof(char));
    strcpy(sommet->couleur,couleur);
    sommet->pere = pere;
    return sommet;
}
cokceken
  • 2,068
  • 11
  • 22
1

You forgot to return sommet from the function.

FWIW, any function, which is expected to return some value, if does not return a value, and the return value is used in caller, it invokes undefined behavior.

Quoting C11, chapter §6.9.1, Function definitions

If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

That said,

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261