2

I have a basic structure like this

typedef struct struck {
    char* id;
    char* mat;
    int value;
    char* place;
} *Truck;

And afunction like this which creates a new "instance" of that struct:

Truck CTruck(char* id, char* mat, int value, char* place) {
    Truck nT = (Truck) malloc(sizeof (Truck));
    nT->value = value;
    strcpy(nT->id, id);
    strcpy(nT->mat, mat);
    strcpy(nT->place, place);
    return nT;
}

I'm getting an error in the first strcpy. It compiles without problem.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
MrFabio
  • 586
  • 2
  • 15
  • 31

3 Answers3

11

Your typedef defines Truck as a struct struck *, i.e. a pointer. So it's size will be 4 or 8 depending on the architecture and not the size of the struct

Use sizeof(*Truck) to get the actual size of the struct.

You also need to allocate memory for the characters. The easiest way would be using strdup().

Truck CTruck(const char* id, const char* mat, int value, const char* place) {
    Truck nT = malloc(sizeof (*Truck));
    nT->value = value;
    nT->id = strdup(id);
    nT->mat = strdup(mat);
    nT->place = strdup(place);
    return nT;
}

However, I would suggest changing your typedef so it's an alias for the struct, not for a pointer to it:

typedef struct {
    char* id;
    char* mat;
    int value;
    char* place;
} Truck;

In your function you then use this:

Truck *nT = malloc(sizeof(Truck));
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 1
    +1 And also malloc some space for id, mat and place so the strcpy's don't obliterate random memory. – JeremyP Apr 13 '12 at 15:19
  • 2
    `strdup` ftw; no need to use malloc and that nasty `strcpy` – ThiefMaster Apr 13 '12 at 15:22
  • I have more structs using *Stuff on the end of the typedef, and if I change that to }Truck it gives erros on every of them, and that `malloc(sizeof(Truck))` wont work if I use *Truck – MrFabio Apr 13 '12 at 15:27
  • Alright i guess the problem was also in using the strcpy, i didn't knew that *strdup*, thanks to all – MrFabio Apr 13 '12 at 15:38
  • +1 for telling the person to use `typedef` as an alias for a `struct` – Ed Heal Apr 13 '12 at 15:41
7

nT->id is just a pointer. Need to malloc memory to copy the string into. Ditto for the others.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
4

Your usage of sizeof is incorrect. In general, the argument to malloc() needs to be "the size of that which the returned pointer is pointing at". In other words, you need sizeof *nT. See how that also eliminates repeating the type name (Truck)?

Also, in C you don't need to cast the return value of malloc(); it serves no purpose, can hide an actual error, and makes the code harder to read.

As others have pointed out, you're also not allocating space for any string data, all you have are the pointers in your structure.

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606