realloc()

This is a discussion on realloc() within the C++ Programming forums, part of the General Programming Boards category; Hi again, I know that this is mainly for C, however it asks me to use it in my C++ ...

  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    329

    realloc()

    Hi again,

    I know that this is mainly for C, however it asks me to use it in my C++ book to deal with any overflow going into an array.

    My idea was to have an initial array of size 10 and when reading into it, if the array went over 10 (kept track of by a counter), then I would use re-alloc to change the size of the array. As usual it hasn't worked out quite like I expected

    Code:
    istream& read(istream& is, int* s)
    {
    	int temp;
    	int i = 0;
    	while(is>>temp && temp != '!'){
    		s[i] = temp;
    		++i;
    		if(i > 10) {
    			realloc(s, i*4);
    	}
    	}
    
    	return is;
    	
    }
    Now, as I understand, the 2nd argument for realloc is the size in bytes, so I have set this as i*4 bytes, so if the array goes to size 11 then it should be 11 bytes. However, when I print the array, it is just random trash!

    Any advice please?

    Thanks.

  2. #2
    Registered User
    Join Date
    Feb 2009
    Posts
    329
    Btw, int* s is a pointer to an int array in free store, if it makes any difference.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,659
    You need to pass the pointer by reference, and then you need to make use of the return value of realloc. Furthemore, you need to decide how to handle the case if realloc returns a null pointer (e.g., you might free the existing dynamic array and then... throw an exception?)

    But there's more: you also need to keep track of both the size (as in number of elements in use) and capacity (as in number of elements allocated) of the dynamic array. After all, after you expand the dynamic array, it is still possible that the resulting capacity is not enough.

    I suggest that you just use a std::vector<int> instead. You would be able to use a std::vector of objects of a non-POD class type, but it would be incorrect to use realloc for a dynamic array of objects of a non-POD class type.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User
    Join Date
    Feb 2009
    Posts
    329
    Thanks. I thought by me incrementing i within the loop and then using realloc each loop through once i > 10, would increase it as each new element is added? Is that not the case?

    Thanks,

  5. #5
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,505
    realloc ALSO returns a pointer (to the possibly moved memory)

    So you need to pass your original pointer by reference, AND make sure it is updated.

    You also need to watch out for realloc returning NULL. In this case, the old memory is NOT freed. It is a common error to trash your only pointer with something like
    p = realloc( p, size );


    > so I have set this as i*4 bytes,
    * sizeof(int)
    would be clearer, and more portable.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,659
    Quote Originally Posted by darren78
    I thought by me incrementing i within the loop and then using realloc each loop through once i > 10, would increase it as each new element is added? Is that not the case?
    Ah. Yes, except that it should be:
    Code:
    int* t = realloc(s, i * sizeof(*t));
    if (t) {
        s = t;
    } else {
        // handle the fact that realloc could not realloc.
    }
    But if you do it this way, then after the first ten elements, you will be calling realloc for every subsequent element, which is terribly inefficient. Rather, you should increase the capacity by some factor when necessary, and thus amortise the cost of expanding the dynamic array.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    Feb 2009
    Posts
    329
    Quote Originally Posted by laserlight View Post
    Code:
    int* t = realloc(s, i * sizeof(*t));
    
    }
    When I try this, I get error c2440: cannot convert from void* to int*. I'm unsure why as none of them are declared void?

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,659
    My mistake, or rather, your book's mistake that became my mistake. You need to cast to int* as the return value of realloc is void*, but void* is not implicitly convertible to int* in C++.

    What book is this again?
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Registered User
    Join Date
    Feb 2009
    Posts
    329
    Quote Originally Posted by laserlight View Post
    My mistake, or rather, your book's mistake that became my mistake. You need to cast to int* as the return value of realloc is void*, but void* is not implicitly convertible to int* in C++.

    What book is this again?
    Thanks. It's PPP by Stroustrup.

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,659
    Quote Originally Posted by darren78
    It's PPP by Stroustrup.
    Amazing, as that goes against what he wrote in Learning Standard C++ as a New Language. I presume that this is a relatively late chapter, and you merely have not sufficiently practiced the earlier material? After all, by now you should know at least in principle how push_back of std::vector works, and so you should have reached for the size+capacity solution when trying to imitate it with realloc, as it would have been explained to you how push_back can run in amortised constant time.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User
    Join Date
    Feb 2009
    Posts
    329
    Quote Originally Posted by laserlight View Post
    Amazing, as that goes against what he wrote in Learning Standard C++ as a New Language. I presume that this is a relatively late chapter, and you merely have not sufficiently practiced the earlier material? After all, by now you should know at least in principle how push_back of std::vector works, and so you should have reached for the size+capacity solution when trying to imitate it with realloc, as it would have been explained to you how push_back can run in amortised constant time.
    Yeah, I know all about how vectors work, etc and size(), etc. I think for this section, and just in this one particular exercise, he asks us to create an array on the free store and to look up realloc as a way of dealing with any overflow from what the array was initialised to. it's not something that he is particularly teaching, I don't think.

  12. #12
    Registered User
    Join Date
    Feb 2009
    Posts
    329
    Sorry, just re-reading your previous comment. I know how to use push_back but nothing in the book has been said yet on how exactly it works. I think the next few chapters that I am yet to read go over the creation of vectors.

  13. #13
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,673
    Quote Originally Posted by darren78 View Post
    Yeah, I know all about how vectors work, etc and size(), etc. I think for this section, and just in this one particular exercise, he asks us to create an array on the free store and to look up realloc as a way of dealing with any overflow from what the array was initialised to. it's not something that he is particularly teaching, I don't think.
    Still it's amazing that he isn't using the facilities of his own language: new[] and delete[]. You can definitely write this function in terms of that and it would be substantially easier.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. did i understood right this explantion of realloc..
    By transgalactic2 in forum C Programming
    Replies: 3
    Last Post: 10-24-2008, 07:26 AM
  2. writing a pack-style function, any advices?
    By isaac_s in forum C Programming
    Replies: 10
    Last Post: 07-08-2006, 08:09 PM
  3. using realloc
    By bobthebullet990 in forum C Programming
    Replies: 14
    Last Post: 12-06-2005, 04:00 PM
  4. segfault on realloc
    By ziel in forum C Programming
    Replies: 5
    Last Post: 03-16-2003, 03:40 PM
  5. realloc realloc realloc
    By Linette in forum C++ Programming
    Replies: 4
    Last Post: 01-19-2002, 08:18 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21