简体   繁体   中英

Segfault when assigning to char* in struct

So I have a struct "sequence" that has a char* in it. When I try and create a sequence, whenever I try and change the char* it segfaults. Here is the related code. The struct:

typedef struct _sequence {
  unsigned int length;
  unsigned char* bytes;
} Sequence;

The constructor:

Sequence* newSequence(unsigned char firstByte) {      //Creates new  sequence, allocates memory
  printf("Creating new Sequence\n");
  Sequence* seq = (Sequence*)malloc(sizeof(Sequence));
  printf("Have new sequence\n");
  seq->length = 1;
  printf("Set length\n");
  seq->bytes[0] = firstByte;
  printf("Set variables\n");
  return seq;
}

Now I have a main function here just for testing purposes, this file will in the end not have a main function. But here is what i used to testing:

int main() {
  char test[] = "ab";
  printf("Testing sequences!\n");
  Sequence* newSeq = newSequence(test[0]);
  printf("Made new sequence!\n");
  outputSequence(newSeq, stdout);
  printf(" <-- new Sequence created\n");
  return 0;
}

The printfs are again for testing purposes. It always prints out all the way up to "Set length\\n" in the constructor, then segfaults. What am I doing wrong? Thank you!

You allocated apace for the structure correctly, but you didn't allocate any space for the buffer pointed to by the bytes element.

This line invokes undefined behavior because bytes is uninitialized:

seq->bytes[0] = firstByte;

You need to also allocate a buffer and point seq->bytes to it.

Sequence* seq = malloc (sizeof(Sequence));

Here you allocate memory space for one char * , and one int, but you need to allocate space for what you want to store on what is pointed at by your char *, this way :

seq->bytes = malloc (my_string_size);

Only then can you start storing characters in your allocated chunk of memory.

Edit : for instance, to store one single character, you could do :

seq->bytes = malloc(1);
seq->bytes[0] = firstByte;

to use it as a single character. But the good habit in C to manipulate string is to always leave one char more, in that fashion :

seq->bytes = malloc(2);
seq->bytes[0] = firstByte;
seq->bytes[1] = '\0';

The 2nd method looks more like a real 'string' in C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM