0

I am trying to modify a char * that i have in a struct by i am having some issues.

#define MAXLINELENGTH 1000
#define MAXINSTRUCTIONS 65536

struct labelMem {
    char *name;
    int pc;
};

struct labelStr {
    struct labelMem labels[MAXINSTRUCTIONS];
};




while (func(string s) == 0) {
    strncpy(programLabels.labels[labelCounter].name, label, MAXLINELENGTH);
        labelCounter++;
}

I tried a few different ways of arranging my structs in an array but each time i have issues modifying my char * var.

Any ideas on how to fix this would be appreciated.

Chase
  • 33
  • 2
  • 11
  • 3
    You need to allocate memory for `name` inside `labelMem` struct – P0W May 07 '18 at 05:09
  • Either allocate memory for `name` or make it an array. You can't just store data to a pointer like that, it must be pointing some memory space where the data can fit. – Havenard May 07 '18 at 05:11
  • Ok yea that makes sense. Ive done a lot of coding in c++ so i sometimes forget the basics. – Chase May 07 '18 at 05:24
  • If you have `label` and have not yet allocated, then allocate for `strlen (label) + 1` and then just `strcpy` - no need to `strncpy` at that point. (and you know there is NO `string` type in C, so you must already have a `typedef` somewhere? if so, see [Is it a good idea to **typedef** pointers?](http://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers)) – David C. Rankin May 07 '18 at 05:35
  • Or as you know the length, you might as well just use `memcpy` for the `length + 1`. Btw, using `strncpy` is almost always *wrong*. `strncpy` is not "safe strcpy". – Antti Haapala -- Слава Україні May 07 '18 at 06:28

1 Answers1

2

Without a call to malloc pointers do not actually point to anything.

You need to allocate memory for a pointer before you use it. You could change your program to

while (func(string s) == 0) {
    // Allocate memory and check for errors
    programLabels.labels[labelCounter].name = malloc (strlen (label) + 1);
    if (!programLabels.labels[labelCounter].name) { /* handle error */ }

    strncpy(programLabels.labels[labelCounter].name, label, MAXLINELENGTH);
    labelCounter++;
}
Increasingly Idiotic
  • 5,700
  • 5
  • 35
  • 73
  • 1
    How about `programLabels.labels[labelCounter].name = malloc (strlen (label) + 1); if (!programLabels.labels[labelCounter].name) { /* handle error */ }` then `strncpy`. It would be rather wasteful to allocate `MAXLINELENGTH` every time... (but yes, you are correct that it needs to be allocated) – David C. Rankin May 07 '18 at 05:32
  • oops. I should have paid closer attention! – Increasingly Idiotic May 07 '18 at 05:40
  • That's OK, it takes a while to snap to those things. You just kinda have to run through a loop of the code in your head to make sure all the pieces fit. – David C. Rankin May 07 '18 at 05:41