Does the memory address of an object stay intact over its lifetime? - iphone

I am not sure if the memory address of an object keeps beeing the same over its lifetime. Does it? Or does it change sometimes during the object's existence?

Yes, the address of any given object is constant in Objective-C. This is rather important since objects are always referred to by address. :-) (Garbage collectors which move things about and update all pointers to them exist, but garbage collection isn’t supported on the iPhone and the Mac Obj-C garbage collector is documented not to do that – see Garbage Collection Programming Guide: Architecture, under How the Garbage Collector Works.)

If you mean self, then, yes, it stays intact over the lifetime of the object.

Although I have not gone indepth in the matter my views are as under:
Memory addresses of an object may not be static.
For example in Java, objects don't have pointers but references, the JVM might move around objects as part of its memory management scheme and might change the reference value in accordance to the moved object.
Also objects might be moved around as part of the Garbage collection procedure of the JVM.
Although I have not read of any official documentation on this, in case you come across the same you could post it here.
The same process might be taking place in .Net.

In the Cocoa Garbage Collection Programming Guide I'm not seeing quite the ironclad assurance that Ahruman makes above that an object address is guaranteed permanent:
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/GarbageCollection/Articles/gcArchitecture.html
Closed vs. Open Systems section:
'[In an open garbage collection system, collectors] reallocate and copy blocks of memory and update each and every referring pointer to reflect the new address. [...] Cocoa's garbage collector strikes a balance between being “closed” and “open” by knowing exactly where pointers to scanned blocks are wherever it can, by easily tracking "external" references, and being "conservative" only where it must.'
And with the general "dynamic" nature of the Cocoa runtime, I'd want a really explicit discussion of the subject in Apple documentation even for non-garbage-collected program. I don't find any statements along the lines of "the memory address of an object is guaranteed not to change" in searching the whole of developer.apple.com -- try Google with:
site:developer.apple.com cocoa "object's memory address" OR "memory address of an object" guaranteed OR permanent
And then there's that scary subject of... multi-threading (ahhhh).

Related

POSIX mq_timedsend what happens to msg_ptr?

I am trying to debug a potential memory leak. I can see that the msg_ptr is not freed manually after the call to mq_timedsend.
My question is does mq_timedsend free the message after sending it to the queue?
No, it does not free the message, and neither should it - for any number of reasons!
The object referenced may not have been dynamically allocated in the first instance.
It cannot safely assume that the caller is no longer using the object pointed to by msg_ptr.
It cannot know that it is not a pointer to a C++ object requiring a destructor to to be called, rather than simply freeing the memory block.
In short it would be inappropriate and dangerous for any library function to behave in the way you suggest. As a general principle, dynamically allocated memory should be deleted by its owner unless there is some clear and documented protocol for ceding ownership - which is not a common pattern.
In this case the data is copied to the message queue, so you are free to modify or release whatever msg_ptr references after sending.

automatic C++ memory/object instance management? smart pointers?

I would like to have automatic memory disposal in my C++ project.
I don't mind to have some additional conventions in order to obtain this automatic memory disposal - to be specific, I don't mind to have some special coding on creating new object instances (but of course, not anything more as it defeats the purpose).
After some readings on many useful discussions in stackoverflow, I found out that "smart pointers" are referred to the most (along with some reference of third-party c++ garbage collectors).
With only some "textbook" C++ knowledge equipped, I believe that the C++ GCs' complexities make them doesn't worth to be used, in my case.
On the other hand, I have a .NET/Java background, and would like to leverage this experience on C++ too. I'm accustomed to creating object instances and pass them to other classes/functions (I believe it is some bread-and-butter stuff in C++ too).
So, is smart pointers/shared_ptr/boost what I am looking for?
(note that for memory acquiring I mean doing a MyClass* var = new MyClass(), not malloc().)
Some specific background:
Actually what I exactly am trying to do is to write some library functions which can be used in both C++ projects and iPhone projects (note that these are some purely logical business classes, so there should be no portability issues). Although I believe it is not an area that requires high performance (non-game app of iPhone), I have some concerns on resource usage.
Is there any issue in making use of smart pointers in this situation? Are there any better alternatives?
Consider reference counting? Create a base class that keeps a count of how often it is referenced, and deletes itself when that reference count falls to zero.
class RefCounter
{
public:
RefCounter() : mRefCount(1) { }
virtual ~RefCounter() { }
void retain() { mRefCounter++; }
void release() {
if(mRefCount) mRefCount--;
if(!mRefCount) delete this;
}
protected:
unsigned int mRefCounter;
};
Any referring object that needs the instance would call it's retain() function, and when done, it would call release(). The last object to call release would cause the instance to delete itself. You have to be careful to balance the retains and releases, but this technique is essentially how GC works except that GC implementations hide this reference counting from you.
I learned C++ before automatic GC became all the rage and I've never really warmed to the concept, feeling much more secure knowing exactly when and where each byte of memory was allocated and freed. But that's just me.

What makes NSdata advantageous?

I've been looking through the apple documentation for the NSdata class, and I didn't really find it too enlightening. I know how to use the class but I don't really understand the gravity of the advantages that it may or may not provide. I know its a simple question but perhaps it would be good to have such information as a reference.
Advantages over what? Certainly, it's useful to represent an arbitrary block of data as an object just as it's useful to represent a string, a number, or a value as an object. Memory management becomes simpler and is consistent with memory management for all other objects, and there are a number of useful methods defined.
Say you want to read a binary file into memory. We won't worry about the reasons why -- there are as many reasons as there are data file formats. You'll have to:
Check the size of the file
Allocate a block of memory of the proper size
Open the file
Read the contents into memory
Close the file
Remember to free the memory when you're done with it (a condition that can sometimes be tricky to detect)
(Optional) Worry about whether the block of memory has been modified
With NSData, you can just create a new instance from a path or URL and not have to think about the rest.

Asking if an object is invalid

I am trying to determine if an object is valid. The program has (at least) two threads and one of the threads might invalidate the object by removing it from an NSMutableArray. I need the other thread to check either its existence or validity before acting on it.
You can't. The only way to check if the memory your object pointer has still represents a valid object is to dereference it, but dereferencing an "invalid" object (by which I assume you mean one that has been dealloced) will result in either accessing the memory of a new object that has been allocated in the same location, garbage data that may or may not be identical to a normal object, or an unmapped memory page that will result in an immediate EXEC_BAD_ACCESS.
Any time you are holding a reference to an object you might use in the future you must retain it. If you don't you have not shown any interest or ownership in the object and the system may throw it away at any time.
Using objective C accessors and properties instead of directly setting ivars and using retain/release simplifies doing the right thing quite a bit.
Multi-threaded programming is hard. Hard does not begin to capture how difficult it is. This is the kind of hard in which a general, useable, 'reasonably qualified' way of deterministically adding two different numbers together that are being mutated and shared by multiple threads in bounded time without the use of any special assistance from the CPU in the form of atomic instructions would be a major breakthrough and the thesis of your PhD. A deity of your choice would publicly thank you for your contribution to humanity. Just for adding two numbers together. Actually, multi-threaded programming is even harder than that.
Take a look at: Technical Note TN2059
Using collection classes safely with multithreaded applications. It covers this topic in general, and outlines some of the non-obvious pitfalls that await you.
You say
I need the other thread to check either its existence or validity before acting on it.
The easiest way is to hold on to the index of the object in the NSMutableArray and then do the following
if( myObject == [myArray objectAtIndex: myObjectIndex] ) {
// everything is good !
}
else {
// my object is not what I think it is anymore
}
There are clear problem with this approach however
insertion, and deletion will stuff you up
The approach is not thread safe since the array can be changed while you are reading it
I really recomend using a different way to share this array between the two threads. Does it have to be mutable? If it doesn't then make it immutable and then you no longer have to worry about the threading issues.
If it does, then you really have to reconsider your approach. Hopefully someone can give an cocoa way of doing this in a thread safe way as I don't have the experience.

How can I find memory leaks in long-running Perl program?

Perl uses reference counting for GC, and it's quite easy to make a circular reference by accident. I see that my program seems to be using more and more memory, and it will probably overflow after a few days.
Is there any way to debug memory leaks in Perl? Attaching to a program and getting numbers of objects of various types would be a good start. If I knew which objects are much more numerous than expected I could check all references to them and hopefully fix the leak.
It may be relevant that Perl never gives memory back to the system by itself: It's all up to malloc() and all the rules associated with that.
Knowing how malloc() allocates memory is important to answering the greater question, and it varies from system to system, but in general most malloc() implementations are optimized for programs allocating and deallocating in stack-like orders. Perl uses reference-counting for tracking memory which means that deallocations which means (unlike a GC-based language which uses malloc() underneath) it is actually not all that difficult to tell where deallocation is going to occur, and in what order.
It may be that you can reorganize your program to take advantage of this fact- by calling undef($old_object) explicitly - and in the right order, in a manner similar to the way C-programmers say free(old_object);
For long-running programs (days, months, etc), where I have loads of load/copy/dump cycles, I garbage-collect using exit() and exec(), and where it's otherwide unfeasible, I simply pack up my data structures (using Storable) and file descriptors (using $^F) and exec($0) - usually with an environment variable set like $ENV{EXEC_GC_MODE}, and you may need something similar even if you don't have any leaks of your own simply because Perl is leaking small chunks that your system's malloc() can't figure out how to give back.
Of course, if you do have leaks in your code, then the rest of my advice is somewhat more relevant. It was originally posted to another question on this subject, but it didn't explicitly cover long-running programs.
All perl program memory leaks will either be an XS holding onto a reference, or a circular data structure. Devel::Cycle is a great tool for finding circular references, if you know what structures are likely to contain the loops. Devel::Peek can be used to find objects with a higher-than-expected reference count.
If you don't know where else to look, Devel::LeakTrace::Fast could be a good first place, but you'll need a perl built for debugging.
If you suspect the leak is inside XS-space, it's much harder, and Valgrind will probably be your best bet. Test::Valgrind may help you lower the amount of code you need to search, but this won't work on Windows, so you'd have to port (at least the leaky portion) to Linux in order to do this.
Devel::Gladiator is another useful tool in this space.
Seems like the cpan module Devel::Cycle is what you are looking for. It requires making some changes to your code, but it should help you find your references without too many problems.
valgrind is a great linux application, which locates memory leaks in running code. If your Perl code runs on linux, you should check it out.
In addition to the other comments, you may find my Perl Memory Use talk at LPW2013 useful. I'd recommend watching the screencast as it explains the slides and has some cute visuals and some Q&A at the end.
I'd also suggest looking at Paul Evans Devel::MAT module which I mention in the talk.