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;
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;
}
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;
}
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.