I'm new to c++ currently working on my assignment and encounter this runtime error "Access violation reading location" when trying to assign iterator pointer into array using for loop.
Flist = data.getFList();
for(Fit = Flist.begin(); Fit != Flist.end(); Fit++)
{
++counter;
cout << "(" << counter << ") Destination: " << Fit->getDest() << " [Class: " ><< Fit->getClass() << "]" << endl;
_getch();
fArr[counter] = *Fit;
}
Constructor
Staff::Staff()
{
counter = 0;
fArr = new Flight[counter];
};
Header
Flight *fArr;
int counter;
Any help will be great~
When you allocate memory in the constructor, you're creating an array of 0 size, that doesn't really make sense.
Instead, just use a vector of flights: std::vector<Flight> fArr, and push back to it:
fArr.push_back(*Fit);
Related
Hello I'm trying to rewrite my own memory manager and STL (nothing fancy, just some basic vector and string features) and I'm getting a strange behaviour. I'm trying to get experience in the memory management field because I'm a high school student with time to spare. The problem is, when I create my first variable everything goes perfectly but after creating the second variable, the program crashes while creating the first variable.
String.h/.cpp
class String {
char* pointer_toBuffer = nullptr;
size_t buffer_length = 0;
IAllocator* Allocator;
public:
String(const char* text, IAllocator* Allocator);}
String::String(const char* text, TuranAPI::MemoryManagement::IAllocator* MemoryAllocator) : Allocator(MemoryAllocator) {
std::cout << "String creation has started: " << text << std::endl;
unsigned int i = 0;
while (text[i] != 0) {
i++;
}
buffer_length = i + 1;
pointer_toBuffer = (char*)Allocator->Allocate_MemoryBlock(buffer_length * sizeof(char));//When I write the Second String part, FirstString crashes directly. I use VSDebug and it says access violation here while creating FirstString. It is successful if I delete the SecondString part.
for (unsigned int letterindex = 0; letterindex < i; letterindex++) {
pointer_toBuffer[letterindex] = text[letterindex];
}
pointer_toBuffer[i] = 0;
}
MemoryManagement.h/cpp
TAPIMemoryAllocator::TAPIMemoryAllocator(MemoryBlockInfo MemoryPool_toUse){
std::cout << "TAPIMemoryAllocator is created!\n";
std::cout << "MemoryPool's start pointer: " << MemoryPool_toUse.address << std::endl;
MemoryPool.address = MemoryPool_toUse.address;
MemoryPool.size = MemoryPool_toUse.size;
SELF = this;
}
void* TAPIMemoryAllocator::Allocate_MemoryBlock(size_t size) {
std::cout << "MemoryPool's start pointer: " << MemoryPool.address << std::endl;
std::cout << "A buffer of " << size << " bytes allocation request found in TAPIMemoryAllocator!\n";
if (SELF == nullptr) {
TMemoryManager First(1024 * 1024 * 1024 * 1);
MemoryBlockInfo FirstMemoryBlock;
FirstMemoryBlock.address = SELF->MemoryPool.address;
FirstMemoryBlock.size = size;
Allocated_MemoryBlocks[0] = FirstMemoryBlock;
return (char*)SELF->MemoryPool.address;
}
void* finaladdress = SELF->MemoryPool.address;
for (unsigned int blockindex = 0; blockindex < MAX_MEMORYBLOCKNUMBER; blockindex++) {
MemoryBlockInfo& MemoryBlock = Allocated_MemoryBlocks[blockindex];
finaladdress = (char*)finaladdress + MemoryBlock.size;
if (size <= MemoryBlock.size && MemoryBlock.address == nullptr) {
std::cout << "Intended block's size is less than found memory block!\n";
MemoryBlock.address = finaladdress;
//You shouldn't change Memory Block's size because all of the allocations before this are based upon the previous size!
//You should move all the previous allocated memory to set the size (which is not ideal!)
//If I'd want to find memory leaks causing this, I could write code here to log the leaks!
return MemoryBlock.address;
}
else if (MemoryBlock.size == 0 && MemoryBlock.address == nullptr) {
std::cout << "An empty block is created for intended block! Block's Array index is: " << blockindex << "\n";
std::cout << "MemoryPool's start pointer: " << MemoryPool.address << std::endl << "MemoryBlock's pointer: " << finaladdress << std::endl;
//This means this index in the Allocated_MemoryBlocks has never been used, so we can add the data here!
MemoryBlock.address = finaladdress;
MemoryBlock.size = size;
return MemoryBlock.address;
}
}
//If you arrive here, that means there is no empty memory block in the Allocated_MemoryBlocks array!
std::cout << "There is no empty memory block in the Allocated_MemoryBlocks array, so nullptr is returned!\n";
return nullptr;
}
TMemoryManager::TMemoryManager(size_t Main_MemoryBlockSize) {
if (SELF != nullptr) {
std::cout << "You shouldn't create a MemoryManager!";
return;
}
std::cout << "TMemoryManager is created!\n";
MainMemoryBlock.address = malloc(Main_MemoryBlockSize);
MainMemoryBlock.size = Main_MemoryBlockSize;
SELF = this;
std::cout << "Main Memory Block's start pointer: " << MainMemoryBlock.address << std::endl;
MemoryBlockInfo TuranAPI_MemoryPool;
TuranAPI_MemoryPool.address = MainMemoryBlock.address;
std::cout << "TuranAPI_MemoryPool.address: " << TuranAPI_MemoryPool.address << std::endl;
TuranAPI_MemoryPool.size = 1024 * 1024 * 10;
TAPIMemoryAllocator Create(TuranAPI_MemoryPool);
}
TMemoryManager* TMemoryManager::SELF = nullptr;
TMemoryManager First(1024 * 1024 * 1024 * 1);
Main.cpp
String FirstString("How are you?", TAPIMemoryAllocator::SELF);
std::cout << FirstString << std::endl; //If I delete the below, it prints "How are you?" as expected
String SecondString("I'm fine, thanks!", TAPIMemoryAllocator::SELF);
std::cout << SecondString << std::endl;
Solved: The problem was in Allocator. When allocator goes out of scope, it's Allocate_MemoryBlock function (it's a virtual function, not static) is deleted. I don't know why it doesn't occur when only one String is created (maybe a compiler optimization) but storing Allocator's itself (All of variables was static already) and assinging SELF as stored one's pointer solved the problem.
I have just done a module on pointers and dynamic memory in C++ and am attempting to complete a personal assignment so that I can practice the concepts. The program manages an array of strings that are names. The goal that I set for myself is that the list is stored in the heap (to practice using "new"), and the list is dynamically sized as new names are entered.
Disclaimer: I realize that this is easily accomplished using vectors, and after struggling with this for hours I re-wrote my original code to use a vector for the list with no problems. However I want to learn where my understanding of how pointers work is broken.
The problem that I have with the program is this: I initialize the name array to have zero elements and have a function to add names that handles the dynamic sizing. When first called it seems to re-size the array correctly and add a new name to the the new array. Within the function to add a name, I can print the contents of the new array. I can also re-assign the old array pointer to the address of the new array on the heap. However when I call the print function from main after adding a name to the list, the list does not contain a name. By my understanding, since I'm using pointers I should be updating values directly, so after the add name function terminates, the values should persist. Also, if I attempt to add a second name the program crashes. What am I doing wrong with the handling of memory?
I've searched quite a bit and the closest that I can find for a resolution was this post:
How to make an array with a dynamic size? General usage of dynamic arrays (maybe pointers too)?
I modified my code based on what I understand from that but it still doesn't work properly.
#include <stdio.h>
#include <vector>
#include <iostream>
using namespace std;
void add_name_to_list(string * my_list, size_t * list_size);
string get_name();
void print_names(const string *const my_list, const size_t *const list_size);
int main()
{
string *name_list_ptr {nullptr};
name_list_ptr = new string [0];
size_t name_list_size{0};
size_t *name_list_size_ptr {&name_list_size};
print_names(name_list_ptr, name_list_size_ptr);
add_name_to_list(name_list_ptr, name_list_size_ptr);
print_names(name_list_ptr, name_list_size_ptr);
return 0;
}
void add_name_to_list (string * my_list, size_t *list_size)
{
string new_name{get_name()};
string *new_string_ptr{nullptr};
new_string_ptr = new string [*list_size+1];
// copy existing list into new list
cout << "List size is " << *list_size << " so *list size == 0 is " << (*list_size == 0) << endl;
if(*list_size == 0)
{
new_string_ptr[0] = new_name;
*list_size = *list_size +1;
cout << new_string_ptr[0] << " has been added to position " << *list_size << endl;
}
else
{
print_names(my_list, list_size);
for(size_t i{0}; i < *list_size; i++)
{
cout << "At position " << i << " original list is " << my_list[i] << endl;
new_string_ptr[i] = my_list[i];
cout << "The name " << new_string_ptr[i] << " has been added to position " << i << " of the new list" << endl;
}
new_string_ptr[*list_size - 1] = new_name;
*list_size = *list_size + 1;
}
print_names(new_string_ptr, list_size);
string *temp_ptr{nullptr};
temp_ptr = new string [*list_size-1];
cout << "temp ptr is " << temp_ptr << " and my list is " << my_list << endl;
temp_ptr = my_list;
cout << "temp ptr is " << temp_ptr << " and my list is " << my_list << endl;
my_list = new_string_ptr;
delete [] temp_ptr;
new_string_ptr = nullptr;
print_names(my_list, list_size);
}
string get_name()
{
cin.sync();
cin.clear();
string new_name{};
cout << "\nEnter the full name: ";
getline(cin, new_name);
cin.sync();
cin.clear();
if(new_name.size() <= 1)
return "0";
else
return new_name;
}
void print_names(const string *const my_list, const size_t *const list_size)
{
if(*list_size == 0)
cout << "The list is empty" << endl;
else
for(size_t j{0}; j < *list_size; j++)
cout << j << ". " << my_list[j] << endl;
}
One variation that I've tried based on what I learned from searching is:
cout << "temp ptr is " << temp_ptr << " and my list is " << my_list << endl;
//my_list = new_string_ptr;
//delete [] temp_ptr;
//new_string_ptr = nullptr;
delete [] my_list;
my_list = new string[*list_size];
my_list = new_string_ptr;
print_names(my_list, list_size);
Unfortunately the results are the same.
Without checking the logic of the implementation, your list doesn't update because you are assigning my_list = new_string_ptr; but your function received void add_name_to_list (string * my_list, size_t *list_size).
As you are newcomer to C++ world, let me explain clearly:
list_size is a pointer to a size_t, so if you modify the pointed memory, the change will persist, but if you modify the pointer itself, it will not.
list_size = new size_t; // This change doesn't persist
list_size++; // This change doesn't persist
*list_size++; // This change persists and the value of pointed memory was increased.
With my_list is happening exactly the same, you are trying to modify the pointer itself, not the pointed memory.
So, you should use:
void add_name_to_list (string * &my_list, size_t *list_size)
Or maybe you are more confortable with
void add_name_to_list (string ** my_list, size_t *list_size)
[...]
*my_list = new_string_ptr;
Hope this helps
Can someone help me with this error. I've been up all night trying to get this code to work, can't seem to figure it out.
I am trying to COUT a single value from my vector strut but I keep getting this EXC_BAD_ACCESS error. I used breaks to see if variables are as they should be and they are but the error continues. Can you help me?
vector<department> depart;
depart.push_back(department());
while(lineNum <= lineCount)
{
lineNum = lineNum;
depart[lineNum].dept = sTemp1;
depart[lineNum].building = sTemp2;
depart[lineNum].budget = sTempToInt;
depart.push_back(department());
lineNum++;
}
vector<department> deptVec;
cout << "Vector output: " << deptVec[0].budget;
}
else
{
sTemp1.erase (remove (sTemp1.begin(), sTemp1.end(), ' '), sTemp1.end()); //clean up
//sTemp2.erase (remove (sTemp2.begin(), sTemp2.end(), ' '), sTemp2.end()); //clean up
sTemp2.erase(find_if(sTemp2.rbegin(), sTemp2.rend(), bind1st(std::not_equal_to<char>(), ' ')).base(), sTemp2.end());
sTemp3.erase (remove (sTemp3.begin(), sTemp3.end(), ' '), sTemp3.end()); //clean up
sTempToInt = stoi(sTemp1);//file is instructor
vector<intructor> intruct;
intruct.push_back(intructor()); //Push back new subject created with default constructor.
for(int lineNum = 0; lineNum>= lineCount; lineNum++) //Will create a set of vectors for each line.
{
intruct[lineNum].id = sTempToInt;
intruct[lineNum].name = sTemp2;
intruct[lineNum].dept = sTemp3;
intruct.push_back(intructor()); //Adds a new element:
}
cout << sTempToInt << "\n" << sTemp2 << "\n" << sTemp3 << "\n";
}
The part that is giving me the error is
vector<department> deptVec;
cout << "Vector output: " << deptVec[0].budget;
It is suppose to output a int but throughs an error.
I checked that department.budget is holding the int. Not sure what to try.
The deptVec vector is empty and you are trying to access an element from it. Try pushing values to deptVec before cout.
I fixed the problem. For whatever reason, I was trying to create a new vector after the while loop instead of using the one being used in the while loop.
This is before:
vector<department> deptVec;
cout << "Vector output: " << deptVec[0].budget;
After(what it should be): cout << "Vector output: " << depart[0].dept;
I have such piece of code:
typedef struct reader
{
char name[50];
char card_num[50];
char title[100];
}reader_t;
int main()
{
vector<reader> vec;
ifstream input_file("D:\\lab.txt", ios::binary);
reader_t master[1];
input_file.read((char*)&master, sizeof(master));
for (size_t idx = 0; idx < 1; idx++)
{
reader temp;
strcpy(temp.name, master[idx].name);
strcpy(temp.card_num, master[idx].card_num);
strcpy(temp.title, master[idx].title);
vec.push_back(temp);
cout << "Name: " << master[idx].name << endl;
cout << "Card num: " << master[idx].card_num << endl;
cout << "Title: " << master[idx].title<<endl;
}
cout << vec.size();
getchar();
}
What is does: it reads structures from binary file into an array of structures,copies them into vector and displays structure.And yes, I do need to do like this - I need to store structures from file in vector and this is the only working way to do it I could find(if you can tell, how to read structures to vector directly from file - you are welcome).
So,everything works fine, but the problem is that I need to create a function which would be able to do the same, but with dynamic array.I wrote something like this:
void read_structs(int vec_size)
{
ifstream input_file("D:\\lab.txt", ios::binary);
//Here I commented 2 ways how I tried to create a dynamic array of structs
//reader* master = new reader[vec_size];
//reader* master = (reader*)malloc(sizeof(reader) * vec_size);
input_file.read((char*)&master, sizeof(master));
for (size_t idx = 0; idx < vec_size; idx++)
{
reader temp;
strcpy(temp.name, master[idx].name);
strcpy(temp.card_num, master[idx].card_num);
strcpy(temp.title, master[idx].title);
vec.push_back(temp);
cout << "Name: " << master[idx].name << endl;
cout << "Card num: " << master[idx].card_num << endl;
cout << "Title: " << master[idx].title<<endl;
}
}
And that worked fine too unless I tried to run it.VS wasn't higlighting error in my code, it just was throwing an exception right as the moment when the program tried to access master[0].name.
There is absolutely no point in the temp struct. See, the
vec.push_back(temp);
is already using copy constructor, so copy constructor must work and then the set of strcpy is not doing anything different from that, so just go with
vec.push_back(master[0]).
You can't read into vector directly. You do need to read into temporary. So that is correct. Except I suppose you want to read all entries from the file no matter how many of them there are, so you need to put the read itself also into the loop.
There is not much point in creating an array of one element.
reader_t master[1];
input_file.read((char*)master, sizeof(master));
// ^ you *don't* need & here, arrays degrade to pointers automatically
and
reader_t master;
input_file.read((char *)&master, sizeof(master));
// ^ but you do need & here.
are equivalent. I would go with the later.
So we are basically down to:
reader temp; // calling it temp; the master name makes no sense.
while (input_file.read((char*)&temp, sizeof(temp)))
// read returns input_file and input_file is false if last operation failed
{
vec.push_back(temp);
// verify the stored values by reading back vfrom vec.back().
cout << "Name: " << vec.back().name << endl;
cout << "Card num: " << vec.back().card_num << endl;
cout << "Title: " << vec.back().title<<endl;
}
In the second example, you didn't initialize master, so it obviously crashed.
There is a more C++ approach though. First, you define a read operator for the structure:
std::istream &operator>>(std::istream &in, reader &r) {
return in.read((char *)&r, sizeof(r));
}
and then you simply read the vector using the istream_iterator:
vec.assign(std::istream_iterator<reader>(input_file),
std::istream_iterator<reader>());
and the standard library will generate the above loop for you.
I found a function to resize an array and am having trouble understanding how it works (or if it's working properly). For testing I set the "temp" array to a new value and "startCounter" does get assigned to that value, however the memory location for startCounter doesn't change. Here is my code:
int * startCounter;
void resizeArray(int *&arraySent,int origSize,int newSize) {
output << "&arraySent " << &arraySent << endl;
output << "arraySent[0] " << arraySent[0] << endl;
int* temp = new int[newSize];
output << "&temp " << &temp << endl;
for (int i=0; i<origSize; i++) {
temp[i] = arraySent[i];
}
temp[0]=744;
delete [] arraySent;
arraySent = temp;
output << "&arraySent " << &arraySent << endl;
}
//....
startCounter = new int [3];
startCounter[0]=345;
output << &startCounter << endl;
resizeArray(startCounter,3,10);
output << "startCounter[0]" << startCounter[0] << endl;
output << "&startCounter" << &startCounter << endl;
Here is the output I get from this:
&startCounter 0x60fab8
&arraySent 0x60fab8
arraySent[0] 345
&temp 0x82cfe54
&arraySent 0x60fab8
startCounter[0] 744
&startCounter 0x60fab8
My question is, why does the memory location of startCounter not change from 0x60fab8 after deleting it and assigning it to the new "temp" array? Shouldn't it now become 0x82cfe54?
P.S. I understand about vectors and such but am mainly concerned with understanding how this particular function works.
void resizeArray(int *&arraySent,int origSize,int newSize) {
output << "&arraySent " << &arraySent << endl;
outputs the address of the pointer variable, not the address that it holds.
simply omit the address operator to get the (probably) intended effect
&startCounter is the address of the pointer, not the address it points to. it's value won't change. simply use startCounter.