misspelling problem of "SetUpTestCase" or "TearDownTestCase" - googletest

I was wondering if there would be some kind of warning or something for misspelling SetUpTestCase (or TearDownTestCase)
I was facing a memory leak but also I had deleted all the allocated memory in the TearDownTestCase and it was making no sense. After a lot of searches I figured out it is just because of the spelling. I just had wrote it SetUpTestcase insted of SetUpTestCase!
static SetUpTestCase
{
// allocate some memory
}
static TearDownTestcase // instead of TearDownTestCase
{
// delete allocated memory
}
Here I've corrected the mistake but isn't there something to be done in order to face a warning, error, etc. when something like that happens? For example for SetUp (because it's a virtual function) we can place a override and if some similar misspelling happen, compiler will warn. But in the SetUpTestCase/TearDownTestCase situation (Because the functions are static) this solution can't be used.

Related

Same code won't work (kind of) in a shared library, but works when used directly in the program

I created a scripting language, when it worked perfectly, I put all the code in a shared library, and made a wrapper for it, but the same code won't work in the shared library. I've noticed that the code runs faster in the shared library, but it always crashes, due to memory problems, saying that the index is out of array length, but the very same code runs outside the library perfectly.
I've also noticed that if I reduce the amount of work it has to do, it lasts a bit longer before crashing.
My question here is that what is causing this crash, and how do I stop it from happening?
P.S: I haven't included all code, because the whole code is of 1039 lines (but if you need the code to solve the problem, then I could link to it), but I have tracked the crash to a function. And the confusing this is, that function always crashes on the 821st time it's called, never before, that's for a more optimized code, when the code was not optimized, and used more CPU, it would crash at 702.
Plus: I'm using DMD2, and the functions are exported using extern(C), And I'm testing all this on a Linux system, Ubuntu 14.04. And this is how I compile the library:
dmd -debug -gc "qscript.d" "qcompiler.d" "lists.d" "dllmain.d" "-shared" "-odobj/Debug" "-of/home/nafees/Desktop/Projects/QScr/QScr/bin/Debug/libQScr.so" -w -vcolumns
And is loaded using the dlopen function.
Again if you missed my question: what is causing this crash, and how do I stop it from happening? EDIT: and how can I disable the garbage collector, gc.disable doesn't work, gc is undefined.
EDIT: I have tracked 'why' the crash is occurring, I put up debug code all over the files, just to find out that the garbage collector is messing with the script file that was loaded in the memory. I 'fixed' the problem, not actually, by adding a check. It checks if the script is not 'alright', it reloads it into the memory. This is avoiding the crash, but the problem still exists. This changes the question to:
How can I disable the garbage collector> BTW, I tried gc.disable, but the DMD says that gc is undefined.
You must initialize the runtime when you load your shared library for the first time. To do so you need to add something like that to your library:
private __gshared bool _init = false;
import core.runtime: rt_init, rt_term;
export extern(C) void init()
{
if (!_init) rt_init;
}
export extern(C) void terminate()
{
if (_init) rt_term;
_init = false;
}
I really mean like that and not exactly that. Since we don't know how your scripting engine is used an init counter might also be valid:
private __gshared uint _init;
import core.runtime: rt_init, rt_term;
export extern(C) void init()
{
if (!_init) rt_init;
++init;
}
export extern(C) void terminate()
{
--init;
if (!_init) rt_term;
}
Anyway you should get the idea. The GC was undefined because you don't initialize the low level D runtime.
Solved the problem myself. AS I said in the Question's edit: I tracked the problem to the garbage collector, the garbage collector was messing with the script file that was loaded into the memory, that caused the library to crash, because the garbage collector had removed the script's contents from the memory. To solve this, I added:
import core.memory;
...
GC.disable();
This solved the whole problem.

Why is assigned a nil to singleton's static variable

What is the advantage of using this:
+ (CardPainter*) sharedPainter {
static CardPainter* sp = nil;
if (nil == sp) {
sp = [[CardPainter alloc] init];
}
return sp;
}
instead of this:
+ (CardPainter*) sharedPainter {
static CardPainter* sp = [[CardPainter alloc] init];
return sp;
}
The static variable initialization is performed only once, so I see no advantage of the former.
Well, at a compiler level there's several overlapping reasons… the simplest to think about is that static variables are stored in a dedicated data section of your compiled application, which is just mapped into memory as-is. So the compiler has to know precisely what that is at compile time. The result of any Objective-C method call is unpredictable at compile time by definition and in practice - you never know for sure that something "interesting" won't happen at runtime to change the behaviour of that method call, so you don't know for sure what will be returned.
This is all a bit different from e.g. C++, for various reasons (a key one being that C++ has constructors, whereas Objective-C does not). But even in C++ it's still frowned upon for several reasons:
Constructor order is unpredictable, but it's easy and common to have constructors depend on each other, meaning your program can have undefined behaviour at runtime (including data corruption or crashing).
Initialisation of lots of non-trivial objects can be expensive. Doing it all together at launch time might be efficient, but it makes your app slow to launch, which is far worse.
The latter point applies equally to Objective-C. The more you can avoid doing at launch time, and instead do just-in-time, on-demand, the better the user experience generally is.
[ Note that there is one noteable exception to the "no static object instances" rule, and that's strings, of the #"foo" form. Those are actually encoded in your app's data section as real instances (of a special NSString subclass) that just get mapped in at launch and magically work as-is. But that's very carefully architected and the compiler & runtime are tightly coupled on that aspect, to make sure it all works smoothly. It doesn't and cannot apply generally. ]
Because if you dont ask, you gonna initiatlite "*sp" any time you call the "sharedPainter", losing any data.
So, if you ask if sp is nil and the answer is FALSE means "sp" is already initialized and it return the instance. If the answer is true, that means that sp is not initialized and just in that case you call the init function.

Destroying self from within self

I have an Objective-C class whose instances can detect when they are no longer needed and destroy themselves, but I am looking for a safe way to trigger an object's self-destruction from within the object itself, without somehow "destroying the method that is calling the destruction"... My code looks roughly like this (some removed for brevity):
+ (oneway void)destroyInstance:(id)obj {
printf("Destroying.\n");
if (obj != nil) {
free(obj);
obj = nil;
}
}
- (oneway void)release {
_noLongerRequired = [self determineIfNeeded]; // BOOL retVal
if (_noLongerRequired) {
[self deallocateMemory]; // Free ivars etc (NOT oneway)
[MyClass destroyInstance:self]; // Oneway
}
}
If I call -release, it should return instantly to the main thread (due to the oneway).
Meanwhile, if the instance finds it is no longer needed, it should then call the oneway class method destroyInstance: and remove itself from the runtime. My question is, is this safe?? And have I used oneway correctly? It seems to me there is the possibility of destroying the instance's -release function before it returns, which could be... rather bad..?
(PS: Obviously not looking for anything to do with NSObject, etc :))
This is without a doubt a terrible idea if you want working and maintainable software and unsafe in just about any context. But sometimes terrible, unsafe ideas can be fun on the weekend, so I'll answer the components of the question I can discern.
A method will not get "destroyed" because an instance is deallocated. What can happen is that self can end up pointing to deallocated memory during the execution of a method, which means that accessing self or any instance variables during this time can crash.
As to the rest of your code, there is no reason at all to set obj equal to nil in +destroyInstance, so if you were trying accomplish something in particular (nil'ing out pointers to the object perhaps) that way is not the right way to go about it.
Thinking about the use of oneway, what the language says is that sending this message won't block the calling thread. In the context of releasing objects I think it makes some sense, as presumably the target of the message won't ever be referenced by that thread again. By that logic I'd think your declaration of +destroyInstance is maybe OK. I do wonder if you'd need to provide some sort of synchronization so that there's no retain/release race conditions but thinking about it, taking ownership of an object should probably never be asynchronous.
My personal opinion is that anyone who puts this code into production should probably be fired or sued =P. But if it's only for educational purposes, have fun, and hope this helps.

Why is this Objective-C code allocating GBs of RAM, releasing it later, and not reporting any leaks?

I have inherited some code, and it looks like this:
- (bool)makeOneLevel:(int)nummines objects:(int)numobjects
{
[field release];
state = gameWait;
field = [[MineField alloc] createLevel:nummines objects:numobjects];
if([field rating] == -1)
{
return false;
}
...
There is always one MineField allocated. Whenever you make a new field, the first thing the function does is release the old one. If the function succeeds in making a MineField, then it returns true.
I also have this:
while(numsaved < self.makeNumber)
{
while(![mineView makeOneLevel:self.makeNumMines objects:self.makeNumObjects])
{
}
{
//saving code here
}
numsaved++;
}
Which calls the function until it creates a valid MineField. This all works. But it allocates GBs of RAM while doing it. But the Leaks tool finds no leaks, and when the outer while finishes and the OS gets control back, all that RAM is deallocated just fine.
Am I doing something wrong with the MineField allocation, or should I be looking elsewhere in the creation process?
Without knowing the internals it's impossible to say for sure, but the behavior you're describing sounds like -[MineView makeOneLevel:objects:] is internally allocating and autoreleasing objects. Since the AppKit default event loop creates and cleans up an autorelease pool for each event it processes, everything does end up going away eventually, but not until the event is finished processing (e.g, after your method exits).
The easiest solution will be to wrap your own autorelease pool around the while() loop, and drain it either every time around the loop or periodically. If you aren't too scared of the internals of the method you're calling in the loop, though, you may be better off just finding where it's autoreleasing objects and fix it (by making it explicitly release objects when appropriate).
If you do not get any better answers, try using the heap profiler from Google perftools to track down where the huge allocations are happening.

Why does a passed-by-value struct parameter get corrupted?

This isn’t the original code (I stripped things back in trying to simplify for debugging), but it does display the problem. On the face of it, looks simple enough:
- (void) testMethod: (TouchData) toi {
TouchData newToi = toi;
NSString *test = #"test string";
NSLog(#"string: %#", test);
// in ‘real’ code I pass the struct back
// It’s void here for the simplest possible
// case
}
TouchData is a struct, declared thus:
typedef struct {
Entity *owner;
CGPoint startPos;
CGPoint latestPos;
CGPoint startOfStraightSwipePos;
NSTimeInterval startTime;
NSTimeInterval latestTime;
NSTimeInterval startOfStraightSwipeTime;
CGFloat latestSpeed;
NSMutableArray *gestures;
BOOL isOfInterest;
} TouchData;
When I step through testMethod in the debugger (watching toi) on hitting NSLog (which doesn't even involve toi), all toi member values suddenly zero out. This doesn’t happen to the copy (newToi). It doesn’t happen if I pass the struct in by reference. It doesn’t happen if replace the testMethod invocation directly with the method body (ie. if I run these lines in situ rather than calling into a method). It doesn’t happen if I change the toi parameter type to a dummy struct with a couple of int members, created just before the call.
It might worth pointing out that testMethod is only called from within its own
class, and that the caller has just extracted the struct from an NSMutableDictionary (via unboxing an NSValue). But given that (a) the struct is
passed into the method here by value, and (b) that on entry its members as shown
by the debugger are all as expected, I don’t see that this can be causing a problem. There is also the thorny issue of the two object pointers in the struct, but in other contexts they’re working out OK, and they check out in the debugger on entry to the method, so I don’t think I’ve missed essential retains.
I presume I’m running into some kind of heap or stack corruption, but I’ve no idea how or why. I’m new to Objective-C, and have previously worked in
garbage collected environments, so my memory management experience is limited. It’s entirely possible that I’ve missed something painfully obvious.
I expect someone will tell me to make TouchData an object type instead, and indeed I may well go that way. I also have a couple of tested workarounds, ie. to either work on a copy, or pass the struct in by ref. But I’d really like to know what’s going on here.
If toi is not used after the line TouchData newToi=toi, the compiler can do whatever it wants to do in the stack memory where toi originally was placed after that line. For example, it might reuse the stack memory when calling another function, in this case NSLog.
So, watching toi by a debugger might show something strange. The compiler does often do these things, in particular if the optimization is turned on. Even with no optimization there's no guarantee that the stack location of toi is left intact after it's last used.
By the way, you said having object pointers inside toi didn't cause problems, but it's a tricky situation and I recommend strongly against that practice. Follow the standard retain/release rules; otherwise, another programmer who takes a look at your code (who might be yourself two years from now) would be totally confused. Also, the static analyzer (which can be accessed by doing Build & Analyze in XCode) might be confused and might give false positives. So, don't do that.