Archived

This topic is now archived and is closed to further replies.

Juicy

returning pointers to structs

Recommended Posts

Suppose I want to return a pointer to a struct, which is filled up by reading stuff from a file, thus:
myStruct *fetchStruct( char *path ) {
myStruct *pMyStruct;
FILE *fp;

	fp = fopen(path, "r+b");
	if (fp) {
		pMyStruct = new myStruct;
		fread(head, sizeof(myStruct), 1, fp);
		fclose(fp);
		return pMyStruct;
	}
}
 
Now, the problem I see here is that I''ve dynamically created an instance of myStruct with new and I need to delete it, but I want to pass the data back before I delete it... It seems natural to delete it in the calling function, but I can''t find an example of this happening, so want to clarify it.

Share this post


Link to post
Share on other sites
If you wish to just use it in a function, don''t use new-delete, just use the stack. If you wish to return the data, you must not delete it - the calling function would be given invalid data and heaven knows where that might end up. Delete only once you know the structure will no longer be used, which should very rarely be in the same function call that allocated the memory.

hth

Share this post


Link to post
Share on other sites
The easiest way to do this is to take the struct pointer as a parameter of the function.

void fetchStruct(char* path, myStruct *pMyStruct);
/* the rest is the same, except don''t allocate memory */

Returning pointers from a function can be a bad idea. Local variables go out of scope when the function returns. Returning a pointer to a local variable will often times leave you with a stray pointer.

Share this post


Link to post
Share on other sites
doh.
kdogg, that''s the fella!

I don''t know why I didn''t think of passing the struct back by reference.
Thanks!

Share this post


Link to post
Share on other sites