Why Does Adding 'Dynamic' Fix My Bad Access Issues

Problem with my dynamic array - Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)

You never actually allocate any space for the array variable - you are only declaring it and assigning it a nullptr value. Thus, when you later try executing the array[i]=p; you are trying to dereference a null pointer, which causes your EXC_BAD_ACCESS error.

To fix this, you need to allocate the array, once you know what size it is (i.e. how many sides your polygon has). You should do this in the same way as you allocate the distance array:

    cin>>numberSide;
float* distance=new float[numberSide];
Point* array = new Point[numberSide]; // And you should delete the earlier "Point* array = nullptr;` line

Of course, you also need to free the memory when you have finished with it:

    delete [] distance;
delete [] array;
return 0;

However, as you are using C++, a far better way than using raw pointers and the new operator is to use the Standard Template Library's std::vector container, which takes care of all allocating and freeing operations internally. Here are the relevant 'replacement' lines:

#include <vector> // This header defines the `std::vector` container
//...
cin>>numberSide;
std::vector<float> distance(numberSide);
std::vector<Point> array(numberSide);

Then you don't need the delete[] lines, as the vectors' memory will be released automatically when the vectors go 'out of scope'. Also, you don't need to really change any of your other code, as the std::vector class has a [] operator, which works as you would want it to.

IBOutlet crashing with EXC_BAD_ACCESS even though not nil

Found the offending code, but I don't know why this would cause the errors I was seeing. The drawerController conforms to DrawerViewController protocol, defined as:

protocol DrawerViewController where Self: UIViewController {
func configureDrawer(drawerContainerView: UIView, overlaidView: UIView)
}

When I remove the Where condition, it no longer crashes.

protocol DrawerViewController {
func configureDrawer(drawerContainerView: UIView, overlaidView: UIView)
}

The where clause was not actually necessary for correct function of the program, so I will proceed without it.

UPDATE
I filed a bug with swift.org and received a response. Adding a where clause to a protocol is not supported in Swift 4.2, but will be supported in Swift 5.0. In addition, @J Doe posted below a way to accomplish this with an update to Xcode toolkit.

Why is objc_msgSend causing an EXC_BAD_ACCESS?

You assign the result of your objc_msgSend call to a variable of type id so ARC kicks in and tries to retain the resulting object (crash is in objc_retain as you can see in the stack to the left). However, the result isn’t an object but an integer of value 8, which objc_retain takes to be a pointer. But there are no valid pointers this low, so you get the EXC_BAD_ACCESS.

Just change the type of value to be NSUInteger (or any other non-object type). But make sure all potential selectors return data of the same type. Alternatively, make sure to always return an object (or nil), which can be retained by ARC.

EXC_BAD_ACCESS error for NSManagedObject implementing a protocol in Swift

I found the solution to this issue here:

http://lesstroud.com/dynamic-dispatch-with-nsmanaged-in-swift/

Essentially, this is a quirk of Swift when implementing protocols on Objects that are NSManaged. I had to add the dynamic keyword to my @NSManaged properties in the CurrentUser class, so that the class looked like this:

class CurrentUser: NSManagedObject, UserObject {

@NSManaged dynamic var username: String

}

EXC_BAD_ACCESS when adding object to array

The problem is here:

void addToPersonArray(string name, string age) {
Person person(name, stoi(age));
personArray[personCount] = &person;
}

person is a local variable in the member function addToPersonArray(), which will be destroyed after the function scope.

Hence, storing the address of a local variable(and trying to accessing it latter in printPersonArray()) will give you, nothing but an undefined behavior.

You are lucky that your programme got the exception.


One more thing to note that, you are not actually using your roster to test the program. Instead, all you do is parsing and saving to result vector. You can add this after the while loop, to make it actually work.

if (result.size() == 2) {
roster.addToPersonArray(result[0], result[1]);
}

Suggestion: Since you have a fixed array size, you probably wanna do it with std::array<Person, 5> or with std::vector<Person> by reserving the memory for 5 Person in the c'tor of Roster.

See a sample output: https://wandbox.org/permlink/tAGqqnhCfwz1wPrH

#include <iostream>
#include <sstream>
#include <vector>
#include <array>

class Person {
public:
Person(const std::string& name, int age): name(name), age(age) {}
std::string getName()const { return name; }
void setName(const std::string& n){ name = n; }
int getAge()const { return age; }
void setAge(int a) { age = a; }
private:
std::string name;
int age;
};

class Roster {
public:
Roster() { personArray.reserve(5); } // reserve some memory
void addToPersonArray(const std::string& name, const std::string& age) {
personArray.emplace_back(name, stoi(age));
}
void printPersonArray() {
// use range loop, which will assure, access what you have.
for (const Person& person: personArray)
std::cout << person.getName() << '\t' << person.getAge() << '\n';
}
private:
std::vector<Person> personArray;
//int personCount = 0; --------------> no need anymore
};

int main() {
std::array<std::string,5> studentData{ "Dan,45", "Mark,33", "Mary,22", "April,17", "Jill,22" };
Roster roster;
for(const std::string& str: studentData)
{
std::stringstream ss(str);
std::vector<std::string> result;
while (ss.good()) {
std::string substr;
std::getline(ss, substr, ',');
result.emplace_back(substr);
}
if (result.size() == 2) {
roster.addToPersonArray(result
[0], result[1]);
}
}
roster.printPersonArray();
return 0;
}

Output:

Dan     45
Mark 33
Mary 22
April 17
Jill 22

EXC_BAD_ACCESS when using freed self in dispatch_async

Your understanding of the memory management is correct, that the presence of self in this block will retain self until the dispatched block is completed. The solution is to not retain self while the block runs, by using a weak reference to self inside the block:

__weak typeof(self) weakSelf = self;

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

// do some stuff in background here; when done, then:

dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf addChild:fbFrame];
});
});

You should review that block for any references to self (either explicit or implicitly by referencing an ivar directly), and replace them with weakSelf.

Or, (unlikely in this case) sometimes you'll see the weakSelf/strongSelf pattern where you must ensure that self isn't released during the execution of that nested block:

__weak typeof(self) weakSelf = self;

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

// do some stuff in background here; when done, then:

dispatch_async(dispatch_get_main_queue(), ^{
typeof(self) strongSelf = weakSelf;
if (strongSelf) {
// stuff that requires that if `self` existed at the start of this block,
// that it won't be released during this block
}
});
});

By the way, the other approach is to cancel the network request when the view controller is dismissed. This requires a more significant change (using a NSOperation-based approach rather than GCD; or use NSURLSessionTask-based approach that allows you to cancel the request), but it is the other way to tackle this.

EXC_BAD_ACCESS after storing an object into List in RealmSwift

Gonna need to answer my own question. My issue was in the custom init code of the Goal-object, as it looked like this:

    init(scoreBy:Player, scoreForTeam:GameTeam, passedBy:[Player]?, scoreTime:Date, homeScoreAfter:Int, awayScoreAfter:Int) {
super.init()
...
}

This code does not produce such an realm object that works properly. Creating the Goal-object inline without own init-method solved the issue.


EDIT: The behaviour itself is weird though - should that constructor work, or is this a bug in Realm?



Related Topics



Leave a reply



Submit