File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes C / C++ and the fly likes set to NULL after realloc Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Languages » C / C++
Bookmark "set to NULL after realloc" Watch "set to NULL after realloc" New topic
Author

set to NULL after realloc

Rodrigo Bossini
Ranch Hand

Joined: Jul 03, 2009
Posts: 113
HI,

I have a standard array that sometimes needs to grow so I use realloc.

My problem is the following:

Imagine I have an array with one position that contains a valid object. Now I have a new object that I want to add to the array, but I want it to be in the position, say, 14. I use realloc to get a 15 slots array (0 to 14)
and put the new object in position 14. But now I want all the other positions that originally did not contain valid objects to be set to NULL. Unfortunately realloc does not do that automatically. Do you guys have a suggestion on how to do it? In other words, how do I loop through the new array and check to see which are valid objects and which are not so I can set those invalid to NULL?


I see wind mills
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18978
    
  40



IMO, this is one of the few advantages of using a language that has pointer arithmetic. Simply calculate the range you want to null out, and call bzero() or memset() -- with many compilers, these functions should be mapped to use the processor block instructions.

As for "checking for valid objects"? Do you really need to do that? You just need to zero out any memory that wasn't part of the original array (when array is extended), and zero out the location of the original element that you moved.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: set to NULL after realloc