Swift Singleton Memory Leak - singleton

I'm using a singleton as a container for localization strings, dictionary keys, and notification names used throughout the app. It is initialized as follows:
class ConstantsManager {
private init() {}
class var sharedInstance: ConstantsManager {
struct Static {
static let instance: ConstantsManager! = ConstantsManager()
}
return Static.instance
}
let localization = "NSLocalizedString(etc.)"
let dictKey = "aKey"
let notificationName = Notification.Name("name")
}
The first use of the singleton occurs in AppDelegate's application(_ application: didFinishLaunchingWithOptions:). When Instruments / Leaks reaches
let manager = ConstantsManager.sharedInstance
a leak is indicated. Does the call tree below indicate that initialization is occurring twice? I'm wondering if the properties associated with a second initialization represent the leak. Strangely, the leak doesn't occur on the simulator. (I'm using Xcode 8.2.1 and OS X 10.12.3 for iOS 10.2 deployment.)
Bytes Used # Leaks Symbol Name
448 Bytes 100.0% 14 ConstantsManager.init() -> ConstantsManager
448 Bytes 100.0% 14 ConstantsManager.__allocating_init() -> ConstantsManager
448 Bytes 100.0% 14 globalinit_33_8D935C4E2193156DAA2AB3DF99F55E80_func0
448 Bytes 100.0% 14 static ConstantsManager.(sharedInstance.getter).(Static #1).instance.unsafeMutableAddressor
448 Bytes 100.0% 14 static ConstantsManager.sharedInstance.getter
448 Bytes 100.0% 14 AppDelegate.registerUserDefaults() -> ()
448 Bytes 100.0% 14 AppDelegate.application(UIApplication, didFinishLaunchingWithOptions : [UIApplicationLaunchOptionsKey : Any]?) -> Bool
448 Bytes 100.0% 14 #objc AppDelegate.application(UIApplication, didFinishLaunchingWithOptions : [UIApplicationLaunchOptionsKey : Any]?) -> Bool
448 Bytes 100.0% 14 main

Related

Realm Objective-C migration error

I am seeing crashes via Crashlytics and hearing from customers that the application is crashing right as they open it.
This is narrowed down to the application migrating one of the realm databases. I have not been able to recreate the issue unfortunately because I am not able to make any sense of the error I am seeing.
I have logic that checks when the app starts up to check and see if the realm needs to be compacted. When doing that the realm determines that it needs to be migrated and hit the migration block.
config.migrationBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
if (oldSchemaVersion < 17) {
[migration enumerateObjects:Event.className block:^(RLMObject *oldObject, RLMObject *newObject) {
NSString *className = [[oldObject[#"endDateTime"] objectSchema] className];
if ([className isEqualToString:#"DateObject"]) {
newObject[#"endDateTime"] = oldObject[#"endDateTime"][#"value"];
}
}];
}
};
Due to a mistake on my end when doing previous migrations I was manually checking to see if a property if of a specific type before deciding to migrate it.
Unfortunately when doing so the oldObject which should be of type RLMObject seems to be of type NSTaggedDate according to Crashlytics
[__NSTaggedDate objectSchema]: unrecognized selector sent to instance 0xe41bf592ee000000
Fatal Exception: NSInvalidArgumentException
0 CoreFoundation 0x186419d04 __exceptionPreprocess
1 libobjc.A.dylib 0x185668528 objc_exception_throw
2 CoreFoundation 0x1864271c8 __methodDescriptionForSelector
3 CoreFoundation 0x18641f6b0 ___forwarding___
4 CoreFoundation 0x18630501c _CF_forwarding_prep_0
5 MY_mobile_ios_common 0x10199c8c0 __34+[MYRealm getRealmConfigByName:]_block_invoke_2 (MYRealm.m:44)
6 Realm 0x1011b6598 -[RLMMigration enumerateObjects:block:] (RLMMigration.mm:99)
7 MY_mobile_ios_common 0x10199c830 __34+[MYRealm getRealmConfigByName:]_block_invoke (MYRealm.m:40)
8 Realm 0x1011b6ab4 -[RLMMigration execute:] (RLMMigration.mm:131)
9 Realm 0x1012297ec std::__1::__function::__func<+[RLMRealm realmWithConfiguration:error:]::$_1, std::__1::allocator<+[RLMRealm realmWithConfiguration:error:]::$_1>, void (std::__1::shared_ptr<realm::Realm>, std::__1::shared_ptr<realm::Realm>, realm::Schema&)>::operator()(std::__1::shared_ptr<realm::Realm>&&, std::__1::shared_ptr<realm::Realm>&&, realm::Schema&) (RLMRealm.mm:410)
10 Realm 0x10124fa90 std::__1::__function::__func<realm::Realm::update_schema(realm::Schema, unsigned long long, std::__1::function<void (std::__1::shared_ptr<realm::Realm>, std::__1::shared_ptr<realm::Realm>, realm::Schema&)>, std::__1::function<void (std::__1::shared_ptr<realm::Realm>)>, bool)::$_2, std::__1::allocator<realm::Realm::update_schema(realm::Schema, unsigned long long, std::__1::function<void (std::__1::shared_ptr<realm::Realm>, std::__1::shared_ptr<realm::Realm>, realm::Schema&)>, std::__1::function<void (std::__1::shared_ptr<realm::Realm>)>, bool)::$_2>, void ()>::operator()() (memory:4625)
11 Realm 0x101181f64 realm::ObjectStore::apply_schema_changes(realm::Group&, unsigned long long, realm::Schema&, unsigned long long, realm::SchemaMode, std::__1::vector<realm::SchemaChange, std::__1::allocator<realm::SchemaChange> > const&, std::__1::function<void ()>) (object_store.cpp:753)
12 Realm 0x10124bbb8 realm::Realm::update_schema(realm::Schema, unsigned long long, std::__1::function<void (std::__1::shared_ptr<realm::Realm>, std::__1::shared_ptr<realm::Realm>, realm::Schema&)>, std::__1::function<void (std::__1::shared_ptr<realm::Realm>)>, bool) (functional:1860)
13 Realm 0x101226a10 +[RLMRealm realmWithConfiguration:error:] (functional:1860)
14 MY_mobile_ios_common 0x10199cba0 +[MYRealm mainRealmCompact] (MYRealm.m:137)
15 MY App 0x1002b49dc -[AppDelegate compactRealmIfNeeded] (AppDelegate.m:808)
16 MY App 0x1002af940 -[AppDelegate application:didFinishLaunchingWithOptions:] (AppDelegate.m:48)
Any thoughts on what I could be doing wrong here, am about to just delete the realm databases and force the users to go back through the initial loading of data again.
ProductName: Mac OS X
ProductVersion: 10.12.6
BuildVersion: 16G1036
/Applications/Xcode.app/Contents/Developer
Xcode 9.1
Build version 9B55
/usr/local/bin/pod
1.3.1
Realm (2.10.2)
Realm (= 2.10.2)
/bin/bash
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin16)
(not in use here)
/usr/local/bin/git
git version 2.12.2
The crash log is telling you that your call to [oldObject[#"endDateTime"] objectSchema] is seeing oldObject[#"endDateTime"] evaluate to an NSDate, which does not respond to -objectSchema. If the endDateTime property can be of different types depending on which schema version you're updating from, you'll need to do further checks on the object before sending -objectSchema to it.

Application crashes while saving core data in iOS11

Works perfectly in iOS 10. After I updated my iOS to iOS11 the application is crashing while saving data to core data with an exception.
I have used RZVinyl framework for coredata
BOOL isSaved = [currentContext save:&saveErr];
Assertion failed: (moreParameters->mostRecentEntry ==
CFArrayGetValueAtIndex(stack, stackCount - 1)), function
NSKeyValuePopPendingNotificationPerThread, file
/BuildRoot/Library/Caches/com.apple.xbs/Sources/Foundation_Sim/Foundation-1444.12/EO.subproj/NSKeyValueObserving.m, line 933.
0 libsystem_kernel.dylib 0x00000001826fd348 __pthread_kill + 8
1 libsystem_pthread.dylib 0x0000000182811354 pthread_kill$VARIANT$mp + 396
2 libsystem_c.dylib 0x000000018266cfd8 abort + 140
3 libsystem_c.dylib 0x0000000182640abc basename_r + 0
4 Foundation 0x00000001834f1a9c -[NSRunLoop+ 178844 (NSRunLoop) runUntilDate:] + 0
5 Foundation 0x00000001834df538 NSKeyValueDidChange + 436
6 Foundation 0x0000000183597ae4 NSKeyValueDidChangeWithPerThreadPendingNotifications + 140
7 CoreData 0x00000001854107c8 -[NSManagedObject didChangeValueForKey:] + 120
8 CoreData 0x0000000185416358 -[NSManagedObject+ 844632 (_NSInternalMethods) _updateFromRefreshSnapshot:includingTransients:] + 692
9 CoreData 0x000000018542e054 -[NSManagedObjectContext+ 942164 (_NestedContextSupport) _copyChildObject:toParentObject:fromChildContext:] + 652
10 CoreData 0x000000018542e4bc -[NSManagedObjectContext+ 943292 (_NestedContextSupport) _parentProcessSaveRequest:inContext:error:] + 804
11 CoreData 0x000000018542f3f0 __82-[NSManagedObjectContext+ 947184 (_NestedContextSupport) executeRequest:withContext:error:]_block_invoke + 580
12 CoreData 0x0000000185431644 internalBlockToNSManagedObjectContextPerform + 92
13 libdispatch.dylib 0x0000000182569048 _dispatch_client_callout + 16
14 libdispatch.dylib 0x0000000182571ae8 _dispatch_queue_barrier_sync_invoke_and_complete + 56
15 CoreData 0x000000018541dd10 _perform + 232
16 CoreData 0x000000018542f0e4 -[NSManagedObjectContext+ 946404 (_NestedContextSupport) executeRequest:withContext:error:] + 172
17 CoreData 0x0000000185387ff8 -[NSManagedObjectContext save:] + 2580
NSManagedObjectContext *currentContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[[currentContext userInfo] setObject:self forKey:kRZCoreDataStackParentStackKey];
[self performBlock:^{
BOOL hasChanges = [currentContext hasChanges];
if ( !hasChanges) {
RZVLogInfo(#"Managed object context %# does not have changes, not saving", self);
rzv_performSaveCompletionAsync(completion, nil);
return;
}
NSError *saveErr = nil;
BOOL isSaved = [currentContext save:&saveErr];
if ( !isSaved) {
RZVLogError(#"Error saving managed object context context %#: %#", self, saveErr);
rzv_performSaveCompletionAsync(completion, saveErr);
}
}];
Had the same thing right now and was looking for an answer when I came across your question.
Without any answers to be found I did some in-depth investigation and found the cause (at least in my case).
It turned out that one of the object's relationships was observing KV changes to update the object regarding changes to it's values, and it was also updating a change to the value of the relationship.
That triggered and update on the Object, which caused the relationship to updated with a change, and so on and so forth...
This recursion in KVO caused a crash.
Make sure that if you are observing changes via willChangeValue and didChangeValue to update your relationship regarding this change, don't update if the observer is the one being set.
Does that make sense for you?
Let me know if this is the case and you need a code sample to understand this very confusing answer.
UPDATE:
I know my answer is quite confusing and vague, so I'll add an example.
Consider the following.
We have two example classes which has relationship to each other (i.e reverse relationship):
class A: NSManagedObject {
#NSManaged var id: NSNumber!
#NSManaged var title: String?
#NSManaged var b: B!
override func willChangeValue(forKey key: String) {
super.willChangeValue(forKey: key)
b?.willChangeValue(forKey: "a")
}
override func didChangeValue(forKey key: String) {
super.didChangeValue(forKey: key)
b?.didChangeValue(forKey: "a")
}
}
class B: NSManagedObject {
#NSManaged var id: NSNumber!
#NSManaged var name: String?
#NSManaged var date: Date?
#NSManaged var a: A!
override func willChangeValue(forKey key: String) {
super.willChangeValue(forKey: key)
a?.willChangeValue(forKey: "b")
}
override func didChangeValue(forKey key: String) {
super.didChangeValue(forKey: key)
a?.didChangeValue(forKey: "b")
}
func setNewA(_ newA: A) {
newA.b = self
a = newA
}
}
We use willChangeValue and didChangeValue in each class to notify it's relationship regarding changes in itself.
Now consider the following code:
let b = B(context: context)
let a = A(context: context)
b.setNewA(a)
We use the setNewA function to set the reverse reference.
In the function, first b assigns itself to a.b for the reverse reference and then sets self.a reference.
At this point, a already knows about b.
The later will cause willChangeValue and didChangeValue on b to be called (as we set a). Then a will pick up the update and notify b.
From here on, try can guess how it continues.
This was pretty much what happened to me, with a few minor differences.
I overrode these functions because I am using a NSFetchedResultsController and I needed to pick up on changes in the relationships to update my UI.
It threw me in a loop that caused the crash.
At the end, the fix was rather simple. A was modified to be:
override func willChangeValue(forKey key: String) {
super.willChangeValue(forKey: key)
guard key != "b" else { return }
b?.willChangeValue(forKey: "a")
}
override func didChangeValue(forKey key: String) {
super.didChangeValue(forKey: key)
guard key != "b" else { return }
b?.didChangeValue(forKey: "a")
}
and B was modified the same way, to be:
override func willChangeValue(forKey key: String) {
super.willChangeValue(forKey: key)
guard key != "a" else { return }
a?.willChangeValue(forKey: "b")
}
override func didChangeValue(forKey key: String) {
super.didChangeValue(forKey: key)
guard key != "a" else { return }
a?.didChangeValue(forKey: "b")
}
This prevents each from updating the other once the relationship itself is set (which is redundant, as each is already notified once one of it's properties is set), thus breaking the cycle.
Again, this was the case on my end and this is what fixed it.
Don't know if you're experiencing the issue due to the same reason, but hopefully it'll give you an idea where to look.
Hope it's easier to understand now.
If you're still having trouble understanding, share some code or contact me directly and I'll try and help.

How to fix this memory leaks about strdup

Thanks for your help, the problem has been solved!
I am a new to C, I I wondered why strdup can case memory leaks, because I free it after strup
valgrind code:
==29885==
==29885== HEAP SUMMARY:
==29885== in use at exit: 37 bytes in 2 blocks
==29885== total heap usage: 28 allocs, 26 frees, 17,131 bytes allocated
==29885==
==29885== Searching for pointers to 2 not-freed blocks
==29885== Checked 124,824 bytes
==29885==
==29885== 5 bytes in 1 blocks are indirectly lost in loss record 1 of 2
==29885== at 0x40057A1: malloc (vg_replace_malloc.c:270)
==29885== by 0x2D6B4F: strdup (in /lib/tls/i686/nosegneg/libc-2.3.4.so)
==29885== by 0x804CD3C: new_node (parser.c:355)
==29885== by 0x804C263: identifier (parser.c:75)
==29885== by 0x804940D: yyparse (vtl4.y:111)
==29885== by 0x8049FD4: main (vtl4.y:225)
==29885==
==29885== 37 (32 direct, 5 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2
==29885== at 0x40057A1: malloc (vg_replace_malloc.c:270)
==29885== by 0x804CCEA: new_node (parser.c:347)
==29885== by 0x804C263: identifier (parser.c:75)
==29885== by 0x804940D: yyparse (vtl4.y:111)
==29885== by 0x8049FD4: main (vtl4.y:225)
==29885==
==29885== LEAK SUMMARY:
==29885== definitely lost: 32 bytes in 1 blocks
==29885== indirectly lost: 5 bytes in 1 blocks
==29885== possibly lost: 0 bytes in 0 blocks
==29885== still reachable: 0 bytes in 0 blocks
==29885== suppressed: 0 bytes in 0 blocks
==29885==
==29885== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 12 from 8)
--29885--
--29885-- used_suppression: 12 Ubuntu-stripped-ld.so
==29885==
==29885== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 12 from 8)
new_node (parser.c:355):
struct simpleNode *new_node(JJT jjt,char *node_image){
struct simpleNode *a = malloc(sizeof(struct simpleNode));
if (a==NULL) {
yyerror("FUNC[%s]error:Init a new simple error,out of space!",__func__);
exit(0);
}
a->info.astn = jjt;
a->info.node_name = jjtNodeName[jjt];
**355>>**a->info.image = strdup(node_image);
a->info.already_rendered = cJSON_False;
a->parent = NULL;
a->firstChild = NULL;
a->nextSibling = NULL;
return a;
}
identifier (parser.c:75):
struct simpleNode* identifier(char *identifier){
printf("%s node!key:%s\n",__func__,identifier);
**75>>**struct simpleNode *a = new_node(JJTIDENTIFIER,identifier);
free(identifier);//I free it after use strdup in new_node
return a;
}
the struct simpleteNode :
struct nodeInfo {
char *image;
int already_rendered;//是否已经被渲染过了,防止子节点被重复渲染,默认为cJSON_False
JJT astn;//node编号
const char * node_name;
char *current_tpl_name;
};
struct simpleNode {
struct nodeInfo info;
struct simpleNode* firstChild;//第一个孩子
struct simpleNode* nextSibling;//右兄弟
struct simpleNode* parent;//父亲
};
at last I will free all the pointers
void free_tree(struct simpleNode* n){
//遍历
struct simpleNode *x = n;
if (x) {
//printf("==========Begin to free %s, image=%s=============\n",x->info.node_name,cJSON_Print(x->info.image));
//free_tree(x->firstChild);
//__free(x);
free_tree(x->firstChild);
free_tree(x->nextSibling);
__free(x);
//__free(x);
}
}
void free_nodeInfo(struct simpleNode* n){
if (n!=NULL) {
printf("==============begin delete %s node!\n",n->info.node_name);
struct nodeInfo ni = n->info;
free(ni.image);
// if (ni.current_tpl_name!=NULL) {
// free(ni.current_tpl_name);
// }
free(n);
printf("==============delete node done!\n");
}
}
void __free(struct simpleNode *n){
//printf("==========__free %s, image=%s=============\n",n->info.node_name,cJSON_Print(n->info.image));
//dump_tree(n);
if (n) {
//printf("==============begin delete %s node!\n",n->info.node_name);
free_nodeInfo(n);
}
}
I checked more related issues, but does not solve,please help me!
struct simpleNode* reference_index(struct simpleNode* identifier_n,
struct simpleNode* index_n) {
- struct simpleNode *a = new_node(JJTIDENTIFIER, identifier_n->info.image);//the wrong code
+ struct simpleNode *a = identifier_n;//the right code
struct simpleNode *index = new_node(JJTINDEX, "index");
addChild(index, index_n);
addChild(a, index);
}
I should not be repeated to create a new node a ,because the parameter is already a node identifier_n,when I free identifier_n ,the info.image of node a is already freed,so At this time when I free a->info.image this will cause problems.
I am sorry for my poor English.

Leaks in JVM from Valgrind

First time I used JNI to access a c library and I thought of using valgrind to check for any memory leaks. Valgrind reported so many leaks in jvm.:(
Used Push/Poplocal frame for managing local references and of course releasing references from Get(UTFChars/Arrays) which needs be. Aside from that it also reports a possible lost in AttachCurrentThread method when in fact I detached it successfully through DetachCurrentThread in my call back function.
And now I just need advise/explanation that the reported leaks were not true at all and will not affect my application especially its on the server side. Well for me I suspect that the unloading of the library and destroying had not yet been done after my app exits and valgrind already did its checking part. Hope to hear from anyone who had experience this kind of case as well.
//sample code
void event_callback(void .., int ..)
{
printf("--Enter event_callback Function--\n");
int detach = 0;
//store our jnienv for this thread
JNIEnv *g_env = NULL;
// if our jni env is not attached for this thread, then we will attach it
int getEnvStat = (*g_jvm)->GetEnv(g_jvm, (void **)&g_env, JNI_VERSION_1_6);
if (getEnvStat == JNI_EDETACHED)
{
//if not attached, then lets attached g_env
printf("JNIEnv not attached. Attaching..\n");
if ((*g_jvm)->AttachCurrentThread(g_jvm, (void **) &g_env, NULL) != 0)
{
printf("Failed to attach\n");
return;
}
else
{
detach = 1;
}
}
else if (getEnvStat == JNI_OK)
{
printf("GetEnv: jenv is just OK, already attached.\n");
}
else if (getEnvStat == JNI_EVERSION)
{
printf("GetEnv: version not supported\n");
return;
}
if((*g_env)->PushLocalFrame(g_env, 10)<0)
{
printf("Out of memory\n");
}
//...some useful code here
(*g_env)->PopLocalFrame(g_env, NULL);
if(detach == 1)
{
int result = (*g_jvm)->DetachCurrentThread(g_jvm);
printf("DetachCurrentThread result: %d\n", result);
}
printf("--Exit event_callback Function--\n");
}
Report:
==20914== 432 bytes in 1 blocks are possibly lost in loss record 903 of 1,035
==20914== at 0x4028876: malloc (vg_replace_malloc.c:236)
==20914== by 0x4950461: os::malloc(unsigned int) (in /usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/client/libjvm.so)
==20914== by 0x464470C: CHeapObj::operator new(unsigned int) (in /usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/client/libjvm.so)
==20914== by 0x496BB13: ParkEvent::Allocate(Thread*) (in /usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/client/libjvm.so)
==20914== by 0x4A13CCD: Thread::Thread() (in /usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/client/libjvm.so)
==20914== by 0x4A15091: JavaThread::JavaThread(bool) (in /usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/client/libjvm.so)
==20914== by 0x4853723: attach_current_thread.isra.103.part.104 (in /usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/client/libjvm.so)
==20914== by 0x7B17791: event_callback (in /home/Wrapper/TJNIBridge/libJNIBridge.so)
==20914== by 0x7B44431: xmpp_event_main (my_xmpp.c:562)
==20914== by 0x412146D: clone (clone.S:130)
I also pasted some of the reported leaks below all from jvm lib.
==20914== 4,612 (1,284 direct, 3,328 indirect) bytes in 1 blocks are definitely lost in loss record 1,009 of 1,035
==20914== at 0x4028876: malloc (vg_replace_malloc.c:236)
==20914== by 0x4950461: os::malloc(unsigned int) (in /usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/client/libjvm.so)
==20914== by 0x464470C: CHeapObj::operator new(unsigned int) (in /usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/client/libjvm.so)
==20914== by 0x4A14BE9: WatcherThread::start() (in /usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/client/libjvm.so)
==20914== by 0x4A192DF: Threads::create_vm(JavaVMInitArgs*, bool*) (in /usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/client/libjvm.so)
==20914== by 0x4865BD8: JNI_CreateJavaVM (in /usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/client/libjvm.so)
==20914== by 0x41ECD30: start_thread (pthread_create.c:304)
==20914== by 0x412146D: clone (clone.S:130)
==20914== 8 bytes in 1 blocks are definitely lost in loss record 41 of 1,035
==20914== at 0x4028876: malloc (vg_replace_malloc.c:236)
==20914== by 0x4950461: os::malloc(unsigned int) (in /usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/client/libjvm.so)
==20914== by 0x464470C: CHeapObj::operator new(unsigned int) (in /usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/client/libjvm.so)
==20914== by 0x470E29D: CSpaceCounters::CSpaceCounters(char const*, int, unsigned int, ContiguousSpace*, GenerationCounters*) (in /usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/client/libjvm.so)
==20914== by 0x47A3BF9: DefNewGeneration::DefNewGeneration(ReservedSpace, unsigned int, int, char const*) (in /usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/client/libjvm.so)
==20914== by 0x47FC623: GenerationSpec::init(ReservedSpace, int, GenRemSet*) (in /usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/client/libjvm.so)
==20914== by 0x47EF9D4: GenCollectedHeap::initialize() (in /usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/client/libjvm.so)
==20914== by 0x4B95FF3: ??? (in /usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/client/libjvm.so)
Ubuntu 11.10
OpenJDK 7
The JVM and Valgrind don't get along. Just running the JVM under Valgrind with no input for me gives tons of warnings.
You will need to generate suppressions for the JVM errors.
Try disabling JIT.

OSX - NSLog prevents application crash in debug mode

Developing an app for OSX. There's still bugs and it crashes in release builds.
However, it runs in debug builds, when there's a blank NSLog statement in a few spots. If the NSLog statements are removed, the app crashes on run.
The first statement, in a run loop (prints calculated ticks and drawn frames, it simulates a fluid in an NSView)
NSLog(#"%d ticks, %d frames", ticks, frames);
The second statement, in the tick method that gets called every loop,
NSLog(#"");
In debug mode, running from Xcode, it works just fine with these two statements. If either is removed, it crashes. After several hours searching, I can't find any reference to apps crashing without blank NSLog statements.
Edit: The final question is: Is there anything I should look out for that might be causing this?
Edit 2: The run and tick methods are
-(void) run {
timeval start = gettime();
timeval end = gettime();
float dt = 1./60;
self.E.dt = dt;
float tick = 1e6*dt;
float unprocessed;
int ticks = 0;
int frames = 0;
timeval now;
while ( TRUE ) {
now = gettime();
unprocessed += diff(end, now)/tick;
end = now;
BOOL shouldRender = true; // set false to limit framerate to tickrate
while ( unprocessed >= 1 ) {
ticks++;
[self tick];
unprocessed -= 1;
shouldRender = true;
}
if ( shouldRender ) {
frames++;
}
if ( diff(start, gettime()) > 1000000 ) {
start.tv_sec += 1;
NSLog(#"%d ticks, %d frames", ticks, frames);
frames = 0;
ticks = 0;
}
}
}
-(void) tick {
NSLog(#"");
NSDictionary* fs = [NSDictionary dictionaryWithObjectsAndKeys:self.u, #"u", self.v, #"v", self.p, #"p", self.T, "#T", nil];
NSDictionary* gs = [self.E evolve:fs];
[self.u swap:[gs objectForKey:#"u"]];
[self.v swap:[gs objectForKey:#"v"]];
[self.p swap:[gs objectForKey:#"p"]];
[self.T swap:[gs objectForKey:#"T"]];
[self.view setNeedsDisplay:YES];
}
Edit 3: This is clearly an issue with LLVM. When I compile with GCC, I get no crash. Unfortunately there's an extraordinary amount of memory leaks now due to no ARC. Confusion level increased.
Edit 4: Backtrace
Crashed Thread: 2
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000010
External Modification Warnings:
Debugger attached to process.
VM Regions Near 0x10:
-->
__TEXT 0000000103a9b000-0000000103a9c000 [ 4K] r-x/rwx SM=COW /Users/USER/Library/Developer/Xcode/DerivedData/Splash-ahjwbarsbqqbuzfcnxstxpslekdi/Build/Products/Debug/Splash.app/Contents/MacOS/Splash
Application Specific Information:
objc_msgSend() selector name: copy
objc[32100]: garbage collection is OFF
Thread 2 Crashed:
0 libobjc.A.dylib 0x00007fff8e43ee90 objc_msgSend + 16
1 com.apple.CoreFoundation 0x00007fff87edf8ac -[__NSPlaceholderDictionary initWithObjects:forKeys:count:] + 668
2 com.apple.CoreFoundation 0x00007fff87efcd13 +[NSDictionary dictionaryWithObjectsAndKeys:] + 1203
3 com.mbarriault.Splash 0x0000000103a9d488 -[Game tick] + 328 (Game.m:95)
4 com.mbarriault.Splash 0x0000000103a9d2a9 -[Game run] + 361 (Game.m:76)
5 com.apple.Foundation 0x00007fff9020874e -[NSThread main] + 68
6 com.apple.Foundation 0x00007fff902086c6 __NSThread__main__ + 1575
7 libsystem_c.dylib 0x00007fff8dba18bf _pthread_start + 335
8 libsystem_c.dylib 0x00007fff8dba4b75 thread_start + 13
Thread 2 crashed with X86 Thread State (64-bit):
rax: 0x0000000103aa5a00 rbx: 0x0000000000000004 rcx: 0x0000000000000000 rdx: 0x0000000000000000
rdi: 0x0000000103aa3071 rsi: 0x00007fff8f9ea7d0 rbp: 0x0000000107b47970 rsp: 0x0000000107b47900
r8: 0x0000000000000004 r9: 0x0000000103aa5ab0 r10: 0x0000000000000001 r11: 0x0000000000000000
r12: 0x0000000000000003 r13: 0x0000000107b47928 r14: 0x0000000107b479a0 r15: 0x0000000107b47980
rip: 0x00007fff8e43ee90 rfl: 0x0000000000010202 cr2: 0x0000000000000010
Logical CPU: 3
I removed ID information and the logs for threads that didn't crash, as the whole log went over the post length limit.
Edit 5: Changing the dictionary creation from NSDictionary:dictionaryWithObjectsAndKeys: to NSDictionary:dictionaryWithObjects:forKeys: seems to have fixed all my problems. I'm not entirely certain why, but I'll take it! Thanks everyone!
Edit 6: The correct answer, believe if you will, was a simple typo in a string.
From the look of the backtrace it is crashing when allocating the NSDictionary. Probably one of the object references being used to initialize the NSDictionary is invalid. If you post code from the tick method it could help narrow down what the problem is. Also, if you try debugging with NSZombie on it could tell us which object type it is crashing on.
Edit:
OK. Now that I see the tick code, I can see the problem. I didn't see it at first, but you are using the c-string "#T", which you probably intended to be #"T".