Segmentation fault when printing out dynamic array

I'm getting a segmentation fault whenever I try to print out the line shown in the "push" function. If I remove the [d->data3] from d->data1[d->data3] and just leave it as d->data1, I get the correct output. But regardless, why doesn't d->data1[d->data3] work, and gives me a segmentation fault? Was my dynamic array not properly allocated?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <stdio.h>
#include <stdlib.h>


typedef struct _data{
	char *data1;
	int data2;
	int data3;
} Data;

void init (Data *d){
	d->data2 = 2;
	d->data1 = (char*)malloc(d->data2*sizeof(char));
	d->data3 = 0;
}

void push ( Data *d, char buffer){
	
	d->data1[d->data3] = buffer;
	printf("The character in data1: %s\n", d->data1[d->data3]);
	d->data3++;
}

int main(int argc, char *argv[]) {
	
	Data d;
	char buffer[300];
	
	init (&d);
	
	while (fgets(buffer, 300, stdin)){
		int i;
		for (i = 0; i < 300; i++)
		if ( (buffer[i] == '(') || (buffer[i] == '{') )
			push (&d, buffer[i]);
	}
}
Last edited on
d->data1[d->data3] is a char, but your printf uses %s, which expects a pointer to a null terminated string. Change line 20 to:
printf("The character in data1: %c\n", d->data1[d->data3]);
Topic archived. No new replies allowed.