Segfault with additional variable?

This is a discussion on Segfault with additional variable? within the C++ Programming forums, part of the General Programming Boards category; Has anyone encountered a situation where simply declaring an additional variable causes a segfault when reading a file? I have ...

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    17

    Segfault with additional variable?

    Has anyone encountered a situation where simply declaring an additional variable causes a segfault when reading a file? I have the following int variables declared:

    Code:
    int array[20], i = 0, numReturned = 0; 
    int killIt = 0, numKilled = 0;
    Simply adding another variable, a, to the above causes a segfault in my program when reading a file with a function.

  2. #2
    Registered User
    Join Date
    Oct 2008
    Posts
    55
    Post the code, preferably the least code that duplicates the problem.

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,439
    If your program is trashing memory, then ANY change at all you make (even apparent useless changes) can tip it over from apparently working to definitely not working.

    Without a reasonable chunck of code - like the whole function reading the file, and all the associated variable declarations, we're not going to tell you anything based on those 2 lines.
    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.

  4. #4
    Registered User
    Join Date
    Oct 2008
    Posts
    17
    I figured as much. I'll just paste the whole code since it's relatively small. This is an assignment for a course, which should be obvious...

    This program reads from a file with multiple lines of single integers and puts them into an array. The array is then displayed and the program prompts to "delete" an occurrence of a certain value. After deletion, every element to the right of that value is shifted one to the left, and however many variables that were deleted are treated as vacant elements at the "end" of the array.

    I can add a variable to other functions, just not under main()..

    Code:
    #include <iostream>
    #include <fstream>
    #include <iomanip>
    
    using namespace std;
    
    void fillDisplayArray(int fillit[], int& howMany);
    void removeAll(int arrayData[], int numInArray, int removeIt, int& numRemoved);
    
    int main()
    {
    
    int array[20], i = 0, numReturned = 0; 
    int killIt = 0, numKilled = 0;
    
    fillDisplayArray(array, numReturned); 
    
    cout << "\nThere are a total of " << numReturned << " elements in the file\nwhich were loaded into an array."
    << "\n\nWhich occurrence of an integer would you\nlike to remove from the array?: ";
    cin >> killIt;
    
    removeAll(array, numReturned, killIt, numKilled);
    
    if (numKilled == 0)
    cout << "\nSorry, there are no occurences of " << killIt << " in the array.\n";
    else if (numKilled != 0)
    cout << endl << numKilled << " occurence(s) of " << killIt << " were removed from the array\n"
    	 << "There are now " << numReturned - numKilled << " elements in the array: ";
    	 
    	 cout << "\nThe array now consists of: \n\n";
    	 for (i = 0; i <= numReturned - 1 - numKilled; i++)
    	 {
    	 cout << setw(10) << left << array[i];
    	 if (i == 4 || i == 9 || i == 14)
    	 cout << "\n";
    	 }
    	
    
    return 0;
    } 
    
    void fillDisplayArray(int arrayData[], int& numReturned)
    {
    int i, c = 0;
    ifstream inFile;
    inFile.open("Ch10_Ex5-7Data.txt");
    
    cout << "The following numbers were read from the input file:\n\n"; <--- THIS AREA displays after adding a variable to the code, and then a segfault occurs, when filling the array, it seems
    
    inFile >> arrayData[i];
    while (!inFile.eof())
    {
    cout << setw(10) << left << arrayData[i] ; c++;
    i++;
    inFile >> arrayData[i];
    	if (c == 5)
    	{
    	cout << "\n";
    	c = 0;
    	}
    }
    
    numReturned = i;
    inFile.close();
    }
    
    void removeAll(int arrayData[], int numInArray, int removeIt, int& numRemoved)
    {
    
    	int i, location;
    
    		for (i = 0; i <= numInArray; i++)
    		{
    			if (arrayData[i] == removeIt)
    			{	
    			
    				for (location = i; location < numInArray - 1 ; location++)
    				{
    				arrayData[location] = arrayData[location + 1];
    				}		
    			numRemoved = numRemoved + 1;
    			}
    		}
    
     }

  5. #5
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    And what is your input file?

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  6. #6
    Registered User
    Join Date
    Oct 2008
    Posts
    17
    Quote Originally Posted by matsp View Post
    And what is your input file?

    --
    Mats
    Code:
    76
    89
    150
    135
    200
    12
    100
    28
    178
    189
    167
    134
    175
    150
    87
    99
    129
    149
    176
    35
    I'm creating another program right now dealing with the same input file, and getting a segfault right off the bat with a size 20 array. On the original program if I increase the array to 25, I can add another variable to the program. On this new program, if I increase the variable size to 25, I can just run the program.

  7. #7
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Leading question: What is the value of "i" in your fillDisplayArray?
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  8. #8
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Guessing time! Did you copy/past inFile >> arrayData[i]; instead of cut/copy it inside the while-loop? (you have it twice)

    When you write somewhere you don't allocate then you might get lucky (though, rather really unlucky) and write somewhere that your program is allowed to write. Which you do. If you add more variables, then the above might change, thus causing a segfault (or something like this, not the best explanation)

  9. #9
    Registered User
    Join Date
    Oct 2008
    Posts
    17
    Quote Originally Posted by matsp View Post
    Leading question: What is the value of "i" in your fillDisplayArray?
    32570!

    Well, that's the first time I've ever run into a problem when not assigning a value to a variable when declaring it. I always figured it was unnecessary to do, but got into the habit of it anyway... I just looked right over that one.

    Thanks for revealing that. Lesson learned.

  10. #10
    Registered User
    Join Date
    Oct 2008
    Posts
    17
    Quote Originally Posted by C_ntua View Post
    Guessing time! Did you copy/past inFile >> arrayData[i]; instead of cut/copy it inside the while-loop? (you have it twice)

    When you write somewhere you don't allocate then you might get lucky (though, rather really unlucky) and write somewhere that your program is allowed to write. Which you do. If you add more variables, then the above might change, thus causing a segfault (or something like this, not the best explanation)
    As far as I can tell, it was because i wasn't assigned a value when declared. I set it to zero and can add all the variables I want now. As far as reading initially before a while loop, I read somewhere that it is good practice in certain situations, although I don't do it all the time. It just seems to work better for some files.

  11. #11
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Assigning a value ti variables is a good idea ALWAYS. Whether you initialize them when they are declared, or if you assign a value later is more of coding standards issue. The coding standard I use at work would say that "i" should be declared as close to the first use as possible, and that it should always be initialized. However, by declaring it close to use (instead of at the beginning of the function), we can do things like
    Code:
    int err = SomeFunction();
    rather than
    Code:
        int err = NoError; 
        ... Several lines of other code that doesn't use err. 
        err = SomeFunction();
        if (err != NoError) return err;
        ...
    That way, err is not initialized "unnecessarily".

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  12. #12
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Another thing is that compilers may be able to catch this error if you enable (the right) warnings. E.g VC++ says: "warning C4700: uninitialized local variable 'i' used"
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question about printing a variable???
    By Hoser83 in forum C++ Programming
    Replies: 2
    Last Post: 03-31-2006, 12:57 PM
  2. How accurate is the following...
    By emeyer in forum C Programming
    Replies: 22
    Last Post: 12-07-2005, 11:07 AM
  3. Replies: 2
    Last Post: 04-12-2004, 01:37 AM
  4. write Variable and open Variable and get Information
    By cyberbjorn in forum C++ Programming
    Replies: 2
    Last Post: 04-09-2004, 01:30 AM

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