C: seg fault when filling array inside struct

I have:

1
2
3
4
typedef struct {
  int* data;
  unsigned int len;
} intarr_t;


I do:
1
2
3
4
5
6
7
8
intarr_t* ia=malloc(sizeof(intarr_t);
ia->len =5;
int val=1;
for(int i=0; i<ia->len; i++)
{
  ia->data[i]=val;
  val++;
}


I am getting a seg fault inside the for loop. What are some possible corrections? I have assert statements that pass:

1
2
assert(ia);
assert(ia->data);


I also tried filling the array manually which also causes a segfault:

1
2
3
4
5
ia->data[0]=1;
ia->data[1]=2;
ia->data[2]=3;
ia->data[3]=4;
ia->data[4]=5;


I just figured it out:

I need:
 
ia->data=malloc(sizeof(int)*ia->len);


I need this before filling the array.
Last edited on
The problem is that you haven't allocated space for ia->data:
1
2
3
4
5
6
7
8
9
10
intarr_t* ia=new intarr_t;  // use new/delete instead of malloc/free
ia->len =5;
ia->data = new unsigned int[5]; // allocate space for 5 items
int val=1;

for(int i=0; i<ia->len; i++)
{
  ia->data[i]=val;
  val++;
}
As stated, need to assign a value to ia->data.
1
2
3
4
5
6
7
8
9
    intarr_t* ia = malloc(sizeof(intarr_t));
    ia->len = 5;
    ia->data = malloc(ia->len * sizeof (int));
    int val = 1;
    for (unsigned int i=0; i<ia->len; i++)
    {
        ia->data[i] = val;
        val++;
    }    


Example:
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int* data;
    unsigned int len;
} intarr_t;

void display(intarr_t * intarr);

int main() 
{
    intarr_t one;
    one.len = 5;
    one.data = malloc(one.len * sizeof (int));
    
    one.data[0] = 2;
    one.data[1] = 3;
    one.data[2] = 5;
    one.data[3] = 7;
    one.data[4] = 11;
    
    
    //---------------------------
    
    intarr_t* ia = malloc(sizeof(intarr_t));
    ia->len = 5;
    ia->data = malloc(ia->len * sizeof (int));
    int val = 1;
    for (unsigned int i=0; i<ia->len; i++)
    {
        ia->data[i] = val;
        val++;
    }    
    
    
    //----------------------
    display(&one);
    display(ia);
    
    //--------------
    free (one.data);
    
    free (ia->data);
    free (ia);


  return 0;
}

void display(intarr_t * intarr)
{
    printf("size = %u\n", intarr->len);
    for (unsigned int i=0; i<intarr->len; ++i)
    {
        printf("%5u  %5d\n", i, intarr->data[i]);
    }
}
size = 5
    0      2
    1      3
    2      5
    3      7
    4     11
size = 5
    0      1
    1      2
    2      3
    3      4
    4      5
Topic archived. No new replies allowed.