1

This is where the bug would appear during execution:

C[check].S = vector<int>(S1);

end C is a global struct array and is defined as:

typedef struct C_type{
    double e;
    vector <int> S;
}Cache;
Cache *C;

Now this problem is sometimes it get segmentation fault error, so any hint to fix that? (S1 is not empty and S[check].S is always empty).

chappjc
  • 30,359
  • 6
  • 75
  • 132
Coderzelf
  • 752
  • 3
  • 10
  • 26
  • You can't just declare a pointer and expect it to create the actual object... `new`. – chappjc Sep 23 '14 at 17:24
  • Hi, I initialize the cache with C = (Cache *)malloc(sizeof(Cache)*K*T*T); – Coderzelf Sep 23 '14 at 17:38
  • @chappjc so I should initailize each element with new? Thanks – Coderzelf Sep 23 '14 at 17:39
  • Since this is C++, I'd use `Cache *C = new Cache[K*T*T];` (don't forget to `delete[] C` when you're done with it. The `vector S` needs to be initialized when each `Cache` is created, so I'd [use `new`](http://stackoverflow.com/questions/3575458/does-new-call-default-constructor-in-c). Also have a look at this post on [`struct` in C++](http://stackoverflow.com/q/612328/2778484), which might simplify your struct definition by getting rid of the `typedef`. – chappjc Sep 23 '14 at 17:44
  • Thanks, I used to use malloc() and free(), I guess the reason is malloc didn't consider the dynammic memory consume inside each element so there might be the issue. Now I am changing back to new() and delete [] C. – Coderzelf Sep 23 '14 at 17:49

1 Answers1

1

Since this is C++, use Cache *C = new Cache[K*T*T];. The vector<int> S needs to be initialized when each Cache is created, so use new to accomplish this. The only thing malloc does, is allocate chunks of bytes, but does not initialize the contents.

Don't forget to delete[] C when you're done with it.

Also have a look at this post on struct in C++, which might simplify your struct definition by getting rid of the typedef.

Community
  • 1
  • 1
chappjc
  • 30,359
  • 6
  • 75
  • 132
  • @Coderzelf I'm glad it helped. Once important thing about `new` is that each element will have it's constructor run. In this case, it simply initializes each member (non-trivial for the vector member). Feel free to vote up too if you want! :) – chappjc Sep 24 '14 at 00:10