Answer the question
In order to leave comments, you need to log in
How to fix EXC_BAD_ACCESS (code=1, address=0x0) error?
I want to make merge sort visualization in SFML. I have already made a visualization of quick sort, everything works fine there, and the actions seem to be the same. I have an array of structures, the structure looks like this:
struct elem2
{
sf::RectangleShape shape;
int value;
};
void merge_sort (elem2 a[], int p, int r)
{
if (p < r)
{
int q = (p + r)/2;
merge_sort(a, p, q);
merge_sort(a, q + 1, r);
merge(a, p, q, r);
}
}
int merge (elem2* a, int p, int q, int r)
{
elem2* pq = (elem2*)malloc(sizeof(elem2) * ((q - p) + 1));
elem2* qr = (elem2*)malloc(sizeof(elem2) * (r - q));
sf::Vector2f pos;
int j = p;
for (int i = 0; i < q - p + 1; i++)
{
pq[i] = a[j];
j++;
}
j = q + 1;
for (int i = 0; i < r - q; i++)
{
qr[i] = a[j];
j++;
}
...
struct elem2
{
int shape;
int value;
};
Answer the question
In order to leave comments, you need to log in
You "create" the sf::RectangleShape class via malloc as part of temporary pq, qr arrays. It is filled with garbage. Some of its internal invariants are violated. There can be a lot of problems: starting from the fact that the assignment operator is redefined there, which should clean up something somewhere, ending with the virtual method table of the class being corrupted. Any attempt to do anything with such a class instance is most likely undefined behavior.
If you already use classes from C ++, then you need to allocate memory through new[], and not malloc. Then the class instance will be created normally and the constructor will be called.
One would think that memmove would solve your problem - but again, this violates internal invariants. Any unique_ptr inside will no longer be unique. Such operations with memory can be done only for POD (Plain old data) - structures consisting of structures, arrays and basic types.
Or, better yet, use vector for temporary arrays. Then you don't have to worry about freeing memory. Also, instead of copying, you can use std::move, it may work faster if these sf classes have more efficient move operators.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question