Thread: Memory Issue...?

  1. #1
    Chad Johnson
    Join Date
    May 2004
    Posts
    154

    Unhappy Memory Issue...?

    I have a program writing to a file, and I have several arrays that hold 100 to 2000 elements each. Everything has gone well so far, but now when I try to simply declare another array of 200 elements, part of the file is not written correctly (it is blank at the top in some places). However, when I declare this new array with only 20 elements, the file writes fine.

    What the heck? Why is it doing this? I don't know how I could allocate memory because the arrays are char [] arrays rather than char* arrays, so I can't say

    buffer = (char*) malloc (2000);

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Are the arrays declared within main()?

  3. #3
    i dont know Vicious's Avatar
    Join Date
    May 2002
    Posts
    1,200
    in c++ you could simply use the new operator to allocate memory.

    Code:
    //create a pointer to a "block" of memory
    char *buffer = new char [2000];
    just be sure you delete ( delete [] buffer; ) it when you done.

    also to check if your allocating bad memory.

    Code:
    char *buffer; //create pointer to memory
    
    try {
      buffer = new char [2000]; //allocate memory
      memset(buffer, 0, sizeof(buffer));
    }
    
    catch(bad_alloc & b) {    // catch the exception if something went wrong
      cout << b.what();
    }
    EDIT: also if you need further help, post your code and you will most definately get the answers you seek
    Last edited by Vicious; 08-07-2004 at 01:00 AM.

  4. #4
    Chad Johnson
    Join Date
    May 2004
    Posts
    154
    Yes the arrays are declared within main, so they are not global. I only use these arrays in the main function, and I do declare another variable with the same name inside of another function. I don't think they are conflicting though.

    I will try creating a pointer to a block of memory as well as deleting the array after I am finished with it. We'll see what happens, and if it doesn't work I'll post code.

    Thanks for the help! Much appreciated!


    btw, when you catch exceptions, how do you know the parameters to catch, like "bad_alloc & b", and how do you know the variables inside of the object (such as b)? Never done exception handling before.

  5. #5
    i dont know Vicious's Avatar
    Join Date
    May 2002
    Posts
    1,200
    exceptions usually work like this

    Code:
    #include <iostream>
    #include <string>
    
    //+--Create an exception class---+
    class Exception  
    {
      string errorString;
    
    public:
      string getError( ) {return errorString;}
      Exception(string s);
    };
    
    //+--Call the class constructor---+
    Exception::Exception(string s) { errorString = s }
    
    int main()
    {
      int num1 = 5;
      int num2 = 7;
    
      try {
        if(num1 > num2) 
          std::cout << "The difference is: " << (num1 - num2);
    
        //+----If num1 is not less than num2 we throw our exception object
        else
          throw Exception("The result will be negative");
      }
    
      catch (Exception e) {
        std::cout << e.getError();
      }
    
      return 0;
    }
    and if you ran the program it would output "The results will be negative"

    the new operator happens to throw its own exception automatically.

    Edit: This code is untested and is only an example of how I understand exceptions.
    Last edited by Vicious; 08-07-2004 at 12:59 PM.

  6. #6
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >Yes the arrays are declared within main

    You are probably overflowing the stack. You could either declare the bigger arrays above main(), or use new to create dynamic arrays. A third option is use the STL vector.

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > buffer = new char [2000]; //allocate memory
    > memset(buffer, 0, sizeof(buffer));

    sizeof on a pointer does NOT tell you how many bytes it is pointing to.
    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.

  8. #8
    i dont know Vicious's Avatar
    Join Date
    May 2002
    Posts
    1,200
    Doh, im so sorry. I forgot all about that.

    memset(buffer, 0, 2000);

    Thanks for correcting that slip up Salem

  9. #9
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    >>A third option is use the STL vector.

    And a fourth option, if you're dealing with text (which it sort of looks like, because the arrays are arrays of chars), is to use the std::string
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  10. #10
    Chad Johnson
    Join Date
    May 2004
    Posts
    154

    Exclamation Got it

    I got it! Part of the trouble was that I was using sizeof() to initialize the array elements, and it was taking the size of the variable(s) in bytes. The thing about dynamic memory using new also helped.

    Thanks so much for the help and all the info!

    btw, what I am doing is writing a Bible file using the following (my own) format:

    length of title in bytes (1 byte)
    title (50 bytes)
    length of copyright in bytes (1 byte)
    copyright (50 bytes)
    number of books (2 bytes)
    locations of each book (4 bytes each)
    length of book name in bytes (1 byte)
    book name
    number of chapters in book (2 bytes)
    locations of each chapter (4 bytes each)
    [beginning of chapter]
    number of verses in chapter (2 bytes)
    locations of each verse (4 bytes each)
    length of each verse in bytes (2 bytes)
    verse text

    Also, how do you know when the array is big enough to use new?

  11. #11
    i dont know Vicious's Avatar
    Join Date
    May 2002
    Posts
    1,200
    You could use new to allocate an array of 2 elements if you wish.
    Or you could create a large array by
    Code:
     int array[2000];
    Now, the difference, is where you allocate it.
    I am not comfortable enough with the subject to go into detail, but one method allocates memory on the "heap" and the ofther in the "stack".

    I am not extremely sure about this though.

  12. #12
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    >>btw, what I am doing is writing a Bible file
    I like that I was actually thinking of doing something similar, so I could keep a neat record of any notes I wanted to take while reading, i.e. notes by chapter or by verse, by book, etc. Once you've got this thing written, would you mind giving me a copy?


    >>Also, how do you know when the array is big enough to use new?
    Well, when it's big enough for the program to screw up, then you know to use new But my arrays generally don't exceed 4-5000. There isn't usually a reason for it; sometimes you need a large array to ensure that all input for a line ends up in the same array, etc. but if that's the case, often a std::string will work better because it does everything dynamically anyway. Also, if you can calculate how large an array you need (i.e. you read a header that says '6 bytes for title, 23 bytes for summary') then you can create an array using 'new' that fits exactly. On the other hand, if you know that something will never be more than say 50 characters long, you can create a non-dynamic array of length 51 (for the NULL at the end), because it's 'safer', meaning that it gets destroyed automatically when it goes out of scope. Also, if you want to create the array and have it not disappear after a function returns (so that the calling function can use it), you can allocate it with 'new' - just remember to delete[] it in the calling function.

    **EDIT**
    I think the 'stack' is a block of memory that gets allocated when the program begins; all the variables in the program generally are created on the stack. The 'heap' is a big pile of memory somewhere that is shared by all programs, and when you use 'new', it allocates a block of memory on the heap and returns its memory address (its pointer).

    Hope this helps!
    Last edited by Hunter2; 08-09-2004 at 11:44 AM.
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  13. #13
    Chad Johnson
    Join Date
    May 2004
    Posts
    154
    Quote Originally Posted by Hunter2
    >>Once you've got this thing written, would you mind giving me a copy?
    Sure will. It'll be free. The only thing is I am only able to get my hands on a copy of the King James version, and I don't know where I can get others.

  14. #14
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    Hmm.. well, you could probably get another one from pretty much any bookstore. Except, come to think of it, you probably want to watch out for copyrights. It would be a real bummer if you spent half a year typing it in and then got sued
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  15. #15
    i dont know Vicious's Avatar
    Join Date
    May 2002
    Posts
    1,200
    Are you actually going to type all of this out!?

    If you are, you deserve a freakin cokie or something... I would have just found a PDF or txt file lol.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need Help finding potential Memory issue
    By JoshNCSU22 in forum C Programming
    Replies: 9
    Last Post: 10-29-2008, 09:58 AM
  2. What's the difference?
    By Stonehambey in forum C++ Programming
    Replies: 9
    Last Post: 04-02-2008, 10:26 AM
  3. threads and memory issue
    By Anubhav in forum C Programming
    Replies: 6
    Last Post: 07-25-2006, 04:51 AM
  4. Memory Leak Help
    By (TNT) in forum Windows Programming
    Replies: 3
    Last Post: 06-19-2006, 11:22 AM
  5. Accessing Video Memory Information...need help
    By KneeLess in forum C++ Programming
    Replies: 8
    Last Post: 08-24-2003, 03:53 PM