allocate and deallocate memory in c++ - c++

I'm trying to figure it out why this code doesn't work as it should. I would like to allocate memory for a dictionary file with over 250,000 words. Memory allocation works OK. However free memory doesn't. And, honestly I don't know why. It breaks during deallocation. Below is the code.
Thank you.
#include <iostream> // For general IO
#include <fstream> // For file input and output
#include <cassert> // For the assert statement
using namespace std;
const int NumberOfWords = 500000; // Number of dictionary words
//if i change to == to exact number of words also doesnt work
const int WordLength = 17; // Max word size + 1 for null
void allocateArray(char ** & matrix){
matrix = new char*[NumberOfWords];
for (int i = 0; i < NumberOfWords; i++) {
matrix[i] = new char[WordLength];
// just to be safe, initialize C-string to all null characters
for (int j = 0; j < WordLength; j++) {
matrix[i][j] = NULL;
}//end for (int j=0...
}//end for (int i...
}//end allocateArray()
void deallocateArray(char ** & matrix){
// Deallocate dynamically allocated space for the array
for (int i = 0; i < NumberOfWords; i++) {
delete[] matrix[i];
}
delete[] matrix; // delete the array at the outermost level
}
int main(){
char ** dictionary;
// allocate memory
allocateArray(dictionary);
// Now read the words from the dictionary
ifstream inStream; // declare an input stream for my use
int wordRow = 0; // Row for the current word
inStream.open("dictionary.txt");
assert(!inStream.fail()); // make sure file open was OK
// Keep repeating while input from the file yields a word
while (inStream >> dictionary[wordRow]) {
wordRow++;
}
cout << wordRow << " words were read in." << endl;
cout << "Enter an array index number from which to display a word: ";
long index;
cin >> index;
// Display the word at that memory address
cout << dictionary[index] << endl;
deallocateArray(dictionary);
return 0;
}

The problem is in the following line:
while (inStream >> dictionary[wordRow]) {
There is no limit on the input line length and the application overwrites at least one of string buffers. I would fix it this way:
while (inStream >> std::setw(WordLength - 1) >> dictionary[wordRow]) {
Please do not forget to add
#include <iomanip>
with setd::setw declaration

Related

Process returned -1073741819 (0xC0000005) execution time : 9.933 s error?

I'm not sure why I am getting this error code. I would like help to fix this problem. It runs just fine on my professor's computer but I am not sure why it won't on mine. It should store the items in an array and print the array out in sorted order but it returns that error code.
//
// main.cpp
// Test
//
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
int SIZE;
cout << "Enter Array Size: ";
cin >> SIZE;
//Insert tile into an arrav
string filename;
// Name of the file
cout<<"Enter filename:";
cin>>filename;
string line;
// To read each line from code
int i=0;
//Variable to keen count of each line
string * arr = new string[SIZE];
// arrav to store each line
ifstream mFile (filename);
if (mFile.is_open() ){
while(!mFile.eof()){
getline (mFile, line);
arr[i]=line;
i++;
}
mFile.close();
}
else
cout<<"Couldn't open the file\n";
//sort
string temp;
for (int i=0; i < SIZE; ++i){
for (int j=i+1; j < SIZE; ++j){
if (arr[i] > arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for (int i = 0; i < SIZE; i++)
cout << arr[i] << endl;
return 0;
}
0xC0000005 is EXCEPTION_ACCESS_VIOLATION/STATUS_ACCESS_VIOLATION, it means you're trying to access a memory you have no business going into. This usually happens when using arrays and dereferencing pointers.
In this case, your std::string array named arr is being accessed with an invalid index (probably a number higher than its actual size).
I suggest using breakpoints as it makes everything easier to debug, check the index everytime the breakpoint is hit, until it throws the access violation exception.

Buffer overrun while writing to 'array': the writable size is '1*4' bytes, but '8' bytes might be written

I am filling an empty array with randomly generated numbers between 0 and 100000 but the line "array[i] = rand() % 100000;" has a green underline and says "Buffer overrun while writing to 'array': the writable size is '1*4' bytes, but '8' bytes might be written". Does anyone know how to fix this?
#include <iostream>
#include <Windows.h>
#include <time.h>
#pragma
using namespace std;
int main() {
int N;
cout << "Enter a value for N: ";
cin >> N;
int* array = new int(N);
srand(time(0));
for (int i = 0; i < N; i++) {
array[i] = rand() % 100000;
}
for (int i = 0; i < N; i++) {
cout << array[i] << ", ";
}
delete array;
return 0;
}
new int(N); creates a single int with the initial value N.
For an array, write new int[N];
To free this memory you need to write delete[] array;: the behaviour of delete array; will be undefined.
Note that a drop-in replacement that takes care of all the memory management for you would be
std::vector<int> array(N);

Some test cases aren't passing

#include <iostream>
#include <vector>
int i=0; //points at the current stack that we are working with
int box=0; //no. of boxes held by the crane
int64_t H; //max. height of the stacks given in the que.
int main()
{
int n, value; //storing no. of stacks and creating an additional variable value to store operations
std::cin>> n >> H;
int64_t arr[n]; //storing the no. of boxes each stack has in an array
std::vector<int> arr2; //storing the operations we have to perform in a vector
for(int j=0; j<n; j++){std::cin>> arr[j];} //getting arr
while(std::cin>>value) //getting arr2
{
arr2.push_back(value);
}
for(int xy=0; xy<n; xy++){if(arr[xy]>H){return 0;}} //ensuring that all stacks have no.of boxes less than max. height
if(arr2.size()<1 || arr2.size()>10e5 || n<1 || n>10e5 || H<1 || H>10e8){return 0;} //constraints given in the que.
int k=0; //creating a variable to keep count of how many programs we have already executed
while(k<arr2.size()){
if(arr2[k] == 1){MoveLeft();}
else if(arr2[k]==2){MoveRight(n);}
else if(arr2[k]==3){PickBox(arr, i);}
else if(arr2[k]==4){Dropbox(arr, i);}
else if(arr2[k]==0){k=arr2.size();}
k++;
}
for(int j=0; j<n; j++){std::cout<< arr[j] << " ";} //printing the arr after executing the code
return 0;
}
This is a question from a past year ZCO. And the above code is what I wrote to solve the prob.
The four functions Moveleft, MoveRight, Pickbox, Dropbox have been defined in the same file but aren't shown here because I think there's no issue with them.
When I submit the code, all test cases passed except 2. I don't know what is the problem with my code. Pls help me.
I have tried my best to make the code readable. Sorry if the code looks messy.
With the method you're trying to define an array with a user-input length is unfortunately invalid in C++.
But fortunately, there are basically two methods use to allocate arrays dynamically.
Method 1: Using Vectors
Vector is an important part of C++. It has a lot of features (e.g. its size don't need to be defined static unlike a normal array does, can redefine array size, etc.) An example's given:
#include <iostream>
#include <vector>
int main(void) {
std::vector<int> vArray; // vector<> declaration
int size = 0;
int getInput = 0;
std::cout << "Enter an array size: ";
std::cin >> size;
for (int i = 0; i < size; i++) {
std::cout << "Enter a value: ";
std::cin >> getInput;
vArray.push_back(getInput); // inserts one+ container and data in it
}
for (int i = 0; i < vArray.size(); i++) {
// retrieving contained data...
std::cout << vArray[i] << std::endl;
}
return 0;
}
Method 2: Using 'new' Keyword with Pointed Variable
The simple use of new will help you to achieve your requirement. It's less recommended since already there's concept of vectors which actually works efficiently than arrays. Let's take a look into a simple program:
#include <iostream>
int main(void) {
int *pArray;
int size;
std::cout << "Enter an array size: ";
std::cin >> size;
pArray = new int[size]; // initializing array with dynamic size
for (int i = 0; i < size; i++) {
std::cout << "Enter value: ";
std::cin >> pArray[i];
}
for (int i = 0; i < size; i++) {
std::cout << pArray[i] << std::endl;
}
delete[] pArray;
return 0;
}
Both are nice options to work with, but it's recommended by most using vector<>.

Dynamically allocated array C++ reads a sentence and prints the words

On the input we get a sentence which we read until EOF. We need to add single words to dynamic array and then write them one on each line.
Input: Hello this, is an example.
Output:
Hello
this,
is
an
example
I have the following code and I can't figure out why it doesn't even add anything to the array.
#include <iostream>
#include <string>
using namespace std;
void addToArray(string newWord, string myArray[], int& arrayLength)
{
string * tempArray = new string[arrayLength + 1];
tempArray[arrayLength] = newWord;
for (int i = 0; i < arrayLength; ++i)
{
myArray[i] = tempArray[i];
}
arrayLength++;
myArray = tempArray;
delete [] tempArray;
}
int main()
{
string * arrayOfWOrds = new string[1000];
int arrayLength = 0;
string temp;
while (getline(cin, temp))
{
cout << temp << endl;
addToArray(temp, arrayOfWOrds, arrayLength);
}
cout << "Array" << endl;
for (int i = 0; i < arrayLength; ++i)
{
cout << arrayOfWOrds[i] << endl;
}
}
It's because you don't return the new array from the addToArray function. The change you make only happens in addToArray, it doesn't happen in main.
You also delete[] the wrong array, you delete the array you've just created.
You also copy the array elements in the wrong direction, i.e. from your new array to your old array.
Try this, I've renamed some of the variables for clarity. There is no temporary array in your function only a new array and an old array. Choosing good variable names is very important for writing working code. Bad variable names just confuse yourself.
string* addToArray(string newWord, string* oldArray, int& arrayLength)
{
string * newArray = new string[arrayLength + 1];
newArray[arrayLength] = newWord;
for (int i = 0; i < arrayLength; ++i)
{
newArray[i] = oldArray[i];
}
arrayLength++;
delete [] oldArray;
return newArray;
}
Then use it like this
arrayOfWOrds = addToArray(temp, arrayOfWOrds, arrayLength);
I see several issues here. To begin with, you set arrayLength = 0, so it's not going to iterate over the whole array if you have stuff already in it. If you don't have anything in it, there's no point in making it start off with 1000 items. Also, while (getline(cin,temp)) is an infinite loop, so it will never end and actually print the array. If you want to print the array after each addition, you need to move it into the while loop. There's no real reason to cout the number the user types either; they can already see the line they just typed.
More importantly, there are real issues with the dynamic allocation. You've created a static array (string * arrayOfWOrds = new string[1000];), then you're giving that to the function which makes a new array one item larger, sets the last item in that array to the new value, then iterates over the entire new array and duplicates the values to the old array. Basically, you're just inserting items into the static array at that point, and what you're inserting is a bunch of nothing (because the new array only has one item in it, and it's at arrayLength+1 which is outside the bounds of the original array).
You need to delete the old array, not the new array, which actually should be thrown on the heap and returned.
Basically, it should look more like this:
#include <iostream>
#include <string>
using namespace std;
string* addToArray(string newWord, string myArray[], int& arrayLength)
{
string * returnArray = new string[arrayLength + 1];
returnArray[arrayLength] = newWord;
for (int i = 0; i < arrayLength; ++i)
{
returnArray[i] = myArray[i];
}
arrayLength++;
delete [] myArray;
return returnArray;
}
int main()
{
const int startSize = 0;
string * arrayOfWords = new string[1];
int arrayLength = startSize;
string temp;
cout << "Input: ";
getline(cin, temp);
string word = "";
for (char c : temp){
if (c == ' '){
arrayOfWords = addToArray(word, arrayOfWords, arrayLength);
word = "";
} else word.push_back(c);
}
arrayOfWords = addToArray(word, arrayOfWords, arrayLength); // Don't forget the last word
for (int i = 0; i < arrayLength; ++i)
{
cout << arrayOfWords[i] << endl;
}
}
The array is unchanged, because you pass the pointer to the addToArray function, but it has no way to pass the new pointer back. You can fix this by changing the signature of the function to
void addToArray(string newWord, string *myArray[], int& arrayLength)
You also need to change the code accordingly, and fix problem with deallocation.
You can save yourself all the trouble and use std::vector in place of manually allocated dynamic array:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> arrayOfWOrds;
string temp;
while (getline(cin, temp))
{
cout << temp << endl;
arrayOfWOrds.push_back(temp);
}
cout << "Array" << endl;
for (size_t i = 0; i < arrayOfWOrds.size(); ++i)
{
cout << arrayOfWOrds[i] << endl;
}
}
string in="dasd adas ads adsada adsa asd ads",out;
stringstream ss(in);
vector<string> vr;
while(ss>>out)
{
vr.push_back(out);
//cout<<out<<endl;
}
for(int i=0;i<vr.length();i++)
{
cout<<vr[i]<<endl;
}
try doing this

VC++ Runtime Error : Debug Assertation Failed

Currently I am getting an runtime "assertation error"
Here is the error:
I'm reading words from a text file into dynamically allocated arrays.
this block of code is where I am filling the new arrays.
I know the problem is being caused by this block of code and something about my logic is off just can't see what it is.
//fill new arrays
for( int y = 0; y < new_numwords; y++)
{
for( int i = 0; i < NUM_WORDS; i++)
{
if (!strcmp(SentenceArry[i], EMPTY[0]) == 0)
{
New_SentenceArry[y] = SentenceArry[i];
New_WordCount[y] = WordCount[i];
y++;
}
}
}
Also how would I pass this dynamically allocated 2D array to a function? (the code really needs to be cleaned up as a whole)
char** SentenceArry = new char*[NUM_WORDS]; //declare pointer for the sentence
for( int i = 0; i < NUM_WORDS; i++)
{
SentenceArry[i] = new char[WORD_LENGTH];
}
Here is the full extent of the code.. help would be much appreciated!
Here is what is being read in:
and the current output (the output is how it's suppose to be ):
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <cstring>
#include <cctype>
#include <iomanip>
using std::setw;
using std::left;
using std::cout;
using std::cin;
using std::endl;
using std::ifstream;
int main()
{
const int NUM_WORDS = 17;//constant for the elements of arrays
const int WORD_LENGTH = 50;//constant for the length of the cstrings (NEED TO GIVE THE VALUE ZERO STILL!)
short word_entry = 0; //declare counter
short new_numwords= 0; //declare new word count
char EMPTY[1][4]; //NULL ARRAY
EMPTY[0][0] = '\0';//define it as null
char** SentenceArry = new char*[NUM_WORDS]; //declare pointer for the sentence
for( int i = 0; i < NUM_WORDS; i++)
{
SentenceArry[i] = new char[WORD_LENGTH];
}
int WordCount[NUM_WORDS];//declare integer array for the word counter
for(int i = 0; i < NUM_WORDS; i++)//fill int array
{
WordCount[i] = 1;
}
int New_WordCount[NUM_WORDS] = {0};
ifstream read_text("DataFile.txt"); //read in our text file
if (read_text.is_open()) //check if the the file was opened
{
read_text >> SentenceArry[word_entry];
//REMOVE PUNCTUATION BEFORE BEING READ INTO THE ARRAY
while (!read_text.eof())
{
word_entry++; //increment counter
read_text >> SentenceArry[word_entry]; //read in single words of the text file into the array SentenceArry
char* ptr_ch;//declare our pointer that will find chars
ptr_ch = strstr( SentenceArry[word_entry], ",");//look for "," within the array
if (ptr_ch != NULL)//if true replace it with a null character
{
strncpy( ptr_ch, "\0" , 1);
}//end if
else
{
ptr_ch = strstr( SentenceArry[word_entry], ".");//look for "." within the array
if (ptr_ch != NULL)//if true replace it with a null character
{
strncpy( ptr_ch, "\0" , 1);
}//end if
}//end else
} //end while
}//end if
else
{
cout << "The file could not be opened!" << endl;//display error message if file doesn't open
}//end else
read_text.close(); //close the text file after eof
//WORD COUNT NESTED FOR LOOP
for(int y = 0; y < NUM_WORDS; y++)
{
for(int i = y+1; i < NUM_WORDS; i++)
{
if (strcmp(SentenceArry[y], EMPTY[0]) == 0)//check if the arrays match
{
y++;
}
else
{
if (strcmp(SentenceArry[y], SentenceArry[i]) == 0)//check if the arrays match
{
WordCount[y]++;
strncpy(SentenceArry[i], "\0" , 3);
}//end if
}//end if
}//end for
}//end for
//find how many arrays still contain chars
for(int i = 0; i < NUM_WORDS; i++)
{
if (!strcmp(SentenceArry[i], EMPTY[0]) == 0)
{
new_numwords++;
}
}
//new dynamic array
char** New_SentenceArry = new char*[new_numwords]; //declare pointer for the sentence
for( int i = 0; i < new_numwords; i++)
{
New_SentenceArry[i] = new char[new_numwords];
}
//fill new arrays
for( int y = 0; y < new_numwords; y++)
{
for( int i = 0; i < NUM_WORDS; i++)
{
if (!strcmp(SentenceArry[i], EMPTY[0]) == 0)
{
New_SentenceArry[y] = SentenceArry[i];
New_WordCount[y] = WordCount[i];
y++;
}
}
}
//DISPLAY REPORT
cout << left << setw(15) << "Words" << left << setw(9) << "Frequency" << endl;
for(int i = 0; i < new_numwords; i++) //compare i to the array constant NUM_WORDS
{
cout << left << setw(15) << New_SentenceArry[i] << left << setw(9) << New_WordCount[i] << endl; //display the contents of the array SentenceArry
}
//DEALLOCATION
for( int i = 0; i < NUM_WORDS; i++)//deallocate the words inside the arrays
{
delete [] SentenceArry[i];
}
for(int i = 0; i < new_numwords; i++)
{
delete [] New_SentenceArry[i];
}
delete [] SentenceArry; //deallocate the memory allocation made for the array SentenceArry
delete [] New_SentenceArry;//deallocate the memory allocation made for the array New_SentenceArry
}//end main
There are several issues with the code, not withstanding that this could be written using C++, not C with a sprinkling of C++ I/O..
Issue 1:
Since you're using c-style strings, any copying of string data will require function calls such as strcpy(), strncpy(), etc. You failed in following this advice in this code:
for( int y = 0; y < new_numwords; y++)
{
for( int i = 0; i < NUM_WORDS; i++)
{
if (!strcmp(SentenceArry[i], EMPTY[0]) == 0)
{
New_SentenceArry[y] = SentenceArry[i]; // This is wrong
New_WordCount[y] = WordCount[i];
y++;
}
}
}
You should be using strcpy(), not = to copy strings.
strcpy(New_SentenceArry[y], SentenceArry[i]);
Issue 2:
You should allocate WORD_LENGTH for both the original and new arrays. The length of the strings is independent of the number of strings.
char** New_SentenceArry = new char*[new_numwords]; //declare pointer for the sentence
for( int i = 0; i < new_numwords; i++)
{
New_SentenceArry[i] = new char[new_numwords];
}
This should be:
char** New_SentenceArry = new char*[new_numwords]; //declare pointer for the sentence
for( int i = 0; i < new_numwords; i++)
{
New_SentenceArry[i] = new char[WORD_LENGTH];
}
Issue 3:
Your loops do not check to see if the index is going out of bounds of your arrays.
It seems that you coded your program in accordance to the data that you're currently using, instead of writing code regardless of what the data will be. If you have limited yourself to 17 words, where is the check to see if the index goes above 16? Nowhere.
For example:
while (!read_text.eof() )
Should be:
while (!read_text.eof() && word_entry < NUM_WORDS)
Issue 4:
You don't process the first string found correctly:
read_text >> SentenceArry[word_entry]; // Here you read in the first word
while (!read_text.eof() )
{
word_entry++; //increment counter
read_text >> SentenceArry[word_entry]; // What about the first word you read in?
Summary:
Even with these changes, I can't guarantee that the program won't crash. Even it it doesn't crash with these changes, I can't guarantee it will work 100% of the time -- a guarantee would require further analysis.
The proper C++ solution, given what this assignment was about, is to use a std::map<std::string, int> to keep the word frequency. The map would automatically store similar words in one entry (given that you remove the junk from the word), and would bump up the count to 1 automatically, when the entry is inserted into the map.
Something like this:
#include <string>
#include <map>
#include <algorithm>
typedef std::map<std::string, int> StringMap;
using namespace std;
bool isCharacterGarbage(char ch)
{ return ch == ',' || ch == '.'; }
int main()
{
StringMap sentenceMap;
//...
std::string temp;
read_text >> temp;
temp.erase(std::remove_if(temp.begin(), temp.end(), isCharacterGarbage),temp.end());
sentenceMap[temp]++;
//...
}
That code alone does everything your original code did -- keep track of the strings, bumps up the word count, removes the junk characters from the word before being processed, etc. But best of all, no manual memory management. No calls to new[], delete[], nothing. The code just "works". That is effectively 5 lines of code that you would just need to write a "read" loop around.
I won't go through every detail, you can do that for yourself since the code is small, and there are vast amounts of resources available explaining std::map, remove_if(), etc.
Then printing out is merely going through the map and printing each entry (string and count). If you add the printing, that may be 4 lines of extra code. So in all, practically all of the assignment is done with effectively 10 or so lines of code.
Remove below code.
for(int i = 0; i < new_numwords; i++)
{
delete [] New_SentenceArry[i];
}