bock.steve bock.steve - 4 years ago 85
C Question

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!

Answer Source
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download