So, I am new to C++. I've researched Segmentation Fault (core dumped), memory allocation, and new/delete although I am having trouble understanding the concepts. I do believe my problem lies with memory allocation though and that's why I thought "delete" would have solved my problem. May someone please push me in the right direction?
Input
#include <iostream>
#include <string>
using namespace std;
struct CandyBar
{
string name;
double weight;
int calories;
} ;
int main()
{
CandyBar* backpack = new CandyBar[3];
backpack[0] = {"Choco Chalk", 5.1, 725};
backpack[1] = {"Twisty String", 1.8, 300};
backpack[2] = {"Gummy Nums", 4.4, 475};
cout << "Name\t\tWeight\tCalories" << endl << endl;
for (int x = 0; x < 4; x++)
{
cout << backpack[x].name << "\t" << backpack[x].weight << "\t" << backpack[x].calories << endl;
}
delete backpack;
return 0;
}
Output
Name Weight Calories
Choco Chalk 5.1 725
Twisty String 1.8 300
Gummy Nums 4.4 475
(Segmentation fault) core dumped
I see two bugs:
Your loop for (x = 0; x < 4; x++) will iterate through x values 0, 1, 2, 3. However, since you allocated backpack with new Candybar[3], backpack points to only enough memory to hold 3 CandyBars, namely backpack[0], backpack[1], backpack[2]. As it stands, on its fourth time through, your loop will attempt to access backpack[3], which is off the end of the array.
When you allocate memory with new[] (as you did since you allocated an array of CandyBar), you have to deallocate it with delete[], not just plain delete. See delete vs delete[] operators in C++.
When I changed your loop exit condition to x < 3 and your deallocation to delete[] backpack;, the program worked for me.
Related
The output of the below code is 16. Why so? even without initializing with the length of array of the class the size is 16 and with initializing the length with the 2nd constructor, it is the same size i.e. 16. Any explanation?
#include <iostream>
#include <string>
using namespace std;
template <class T>
class array1{
T * arr;
int l;
public:
array1(){
arr = 0; l=0;
}
array1(int x){
l = x;
arr = new T[l];
}
~array1(){
delete[] arr;
}
void display(){
cout << "array1 is :"<<endl;
for (int i=0; i<l; i++)
cout << arr[i] << " ";
cout << endl;
}
};
int main()
{
array1<int> a1;
cout << "size of int arr is " << sizeof(a1);
return 0;
}
It is because of Data Structure alignment. In your system it is being aligned to 8 bytes word. Print the sizeof(T*) and sizeof(int) it will output 8 and 4 respectively in the constructor of array class. But when output together it takes 16 bytes.
It appears your integer and pointer types are both 8 bytes/64 bits. Also, just a heads up, sizeof is a compile-time operator, meaning that even if an object of your type allocates memory on the heap with the operator new[], sizeof will still return 16 bytes for any object of type array1.
Additionally, no matter what type you have for T, sizeof(array1<T>) will always be 16 bytes. (I am making the assumption that you are not compiling on an atypical target.)
Your class has two member variables. A pointer and an int. I suspect that both are eight bytes in size for your platform.
If so, then: 8 + 8 = 16.
(Your class has no virtual methods -- so no vtable overhead).
my name is Adam, I have just begun to learn C++, I love it, but am only on pg 181 in the seventh edition of sams teach yourself C++ in one hour a day, and pg 102 in the seventh edition of C++ for dummies. I have seven multi page notes on the sams book, and twenty one multi page notes on the for dummies book. Please help me understand why I get 5 errors with my simple program which will be shown shortly. I do not want to use -fpermissive option, I need to learn how to code correctly as I am not very experienced. Thank you everyone, very very much, I absolutely love C++, and even have a very good idea on a simple program I plan to learn how to write, which could allow program development time, or writing time to be reduced by 5-20 times on average. The following program shown is not this program however, but please help me so I may one day write, and use my program idea for a college paper. Thank you again, problem program follows:
#include <iostream>
using namespace std;
int main()
{
cout<< "how many integers do you wish to enter? ";
int InputNums = 0;
cin>> InputNums;
int* pNumbers = new int [InputNums];
int* pCopy = pNumbers;
cout<< "successfully allocated memory for "<<
InputNums<< " integers"<<endl;
for(int Index = 0; Index < InputNums; ++Index)
{
cout<< "enter number "<< Index << ": ";
cin>> *(pNumbers + Index);
}
cout<< "displaying all numbers input: " <<endl;
for(int Index = 0, int* pCopy = pNumbers;
Index < InputNums; ++Index)
cout<< *(pCopy++) << " ";
cout<< endl;
delete[] pNumbers;
cout<< "press enter to continue..." << endl;
cin.ignore(10, '\n');
cin.get();
return 0;
}
The problem is indicated as being in the multiple initializations of the second for loop. Please tell me why my problem program will not compile. Thank you all. Sincerely Adam.
My first advice would be to find a better book.
Once you've done that, forget everything you think you know about using new to allocate an array (e.g., int* pNumbers = new int [InputNums];). It's an obsolete construct that you shouldn't use (ever).
If I had to write a program doing what you've outlined above, the core of it would look something like this:
cout<< "how many integers do you wish to enter? ";
int InputNums;
cin>> InputNums;
std::vector<int> numbers;
int temp;
for (int i=0; i<InputNums; i++) {
cin >> temp;
numbers.push_back(temp);
}
cout<< "displaying all numbers input:\n";
for (auto i : numbers)
cout << i << " ";
Directly answer your question: you cannot initialize variables of different types in the same for loop declaration.
In your example:
for(int Index = 0, int* pCopy = pNumbers;
int and int * are different types. Even if you use auto to let the compiler automatically deduct the types, both variables cannot have different deducted types.
The solution:
int Index = 0;
for(int *pCopy=pNumbers; ...
Having this one single secondary effect: Index is now not only confined to the scope of the for. Should this be a problem, you may do:
{
int Index = 0;
for(int *pCopy=pNumbers; ...
...
}
And now the scope of Index is limited to the surrounding curly braces.
I have 2 std::vectors:
to first vector, I emplace instance
to second vector, I want to store the address of the instance just emplaced
But it does not work, i.e., the stored address differs from the emplaced instance's address.
If it matters at all, I'm on Linux and using g++ 5.1 and clang 3.6 with -std=c++11.
Here's a working example to illustrate the problem.
#include <iostream>
#include <vector>
struct Foo {
Foo(int a1, int a2) : f1(a1), f2(a2) {}
int f1;
int f2;
};
int main(int, char**) {
std::vector<Foo> vec1;
std::vector<Foo*> vec2;
int num = 10;
for (int i = 0; i < num; ++i) {
vec1.emplace_back(i, i * i);
// I want to store the address of *emplaced* instance...
vec2.push_back(&vec1.back());
}
// same
std::cout << "size 1: " << vec1.size() << std::endl;
std::cout << "size 2: " << vec2.size() << std::endl;
// same for me
std::cout << "back 1: " << &vec1.back() << std::endl;
std::cout << "back 2: " << vec2.back() << std::endl;
// typically differ ?
std::cout << "front 1: " << &vec1.front() << std::endl;
std::cout << "front 2: " << vec2.front() << std::endl;
for (int i = 0; i < num; ++i) {
std::cout << i + 1 << "th" << std::endl;
// same for last several (size % 4) for me
std::cout << "1: " << &vec1[i] << std::endl;
std::cout << "2: " << vec2[i] << std::endl;
}
}
Questions
Is it correct behavior ? I guess it's caused by storing the address of temporary instance but I want to know whether it's permitted by the standard (just curious).
If above is true, how to work around this ? I resolved this by changing first one to vector<unique_ptr<Foo>> but is there any idiomatic way ?
Two options:
1) You can simply fix your test. You just need in you test preallocate enough memory first with
vec1.reserve(10);
Well, this is implementation details for std::vector. As more and more items are added to std::vector it needs to get more space for them. And this space must be contigious. So when there is not enough space for a new element std::vector allocates a bigger block of memory, copies existing elements to it, add the new element and finally frees the block of memory that it used before. As a result addresses that you stored in vec2 might become invalid.
However, if you preallocate enough memory for 10 elements then you code is correct.
Or, since reserving memory is sort of tricky thing to do
2) use std::deque since insertion and deletion at either end of a deque never invalidates pointers or references to the rest of the elements (http://en.cppreference.com/w/cpp/container/deque) and forget about the problem with invalidated addresses. So no need to reserve memory.
I wrote the following for a class, but came across some strange behavior while testing it. arrayProcedure is meant to do things with an array based on the 2 "tweaks" at the top of the function (arrSize, and start). For the assignment, arrSize must be 10,000, and start, 100. Just for kicks, I decided to see what happens if I increase them, and for some reason, if arrSize exceeds around 60,000 (I haven't found the exact limit), the program immediately crashes with a stack overflow when using a debugger:
Unhandled exception at 0x008F6977 in TMA3Question1.exe: 0xC00000FD: Stack overflow (parameters: 0x00000000, 0x00A32000).
If I just run it without a debugger, I don't get any helpful errors; windows hangs for a fraction of a second, then gives me an error TMA3Question1.exe has stopped working.
I decided to play around with debugging it, but that didn't shed any light. I placed breaks above and below the call to arrayProcedure, as well as peppered inside of it. When arrSize doesn't exceed 60,000 it runs fine: It pauses before calling arrayProcedure, properly waits at all the points inside of it, then pauses on the break underneath the call.
If I raise arrSize however, the break before the call happens, but it appears as though it never even steps into arrayProcedure; it immediately gives me a stack overflow without pausing at any of the internal breakpoints.
The only thing I can think of is the resulting arrays exceeds my computer's current memory, but that doesn't seem likely for a couple reasons:
It should only use just under a megabyte:
sizeof(double) = 8 bytes
8 * 60000 = 480000 bytes per array
480000 * 2 = 960000 bytes for both arrays
As far as I know, arrays aren't immediately constructed when I function is entered; they're allocated on definition. I placed several breakpoints before the arrays are even declared, and they are never reached.
Any light that you could shed on this would be appreciated.
The code:
#include <iostream>
#include <ctime>
//CLOCKS_PER_SEC is a macro supplied by ctime
double msBetween(clock_t startTime, clock_t endTime) {
return endTime - startTime / (CLOCKS_PER_SEC * 1000.0);
}
void initArr(double arr[], int start, int length, int step) {
for (int i = 0, j = start; i < length; i++, j += step) {
arr[i] = j;
}
}
//The function we're going to inline in the next question
void helper(double a1, double a2) {
std::cout << a1 << " * " << a2 << " = " << a1 * a2 << std::endl;
}
void arrayProcedure() {
const int arrSize = 70000;
const int start = 1000000;
std::cout << "Checking..." << std::endl;
if (arrSize > INT_MAX) {
std::cout << "Given arrSize is too high and exceeds the INT_MAX of: " << INT_MAX << std::endl;
return;
}
double arr1[arrSize];
double arr2[arrSize];
initArr(arr1, start, arrSize, 1);
initArr(arr2, arrSize + start - 1, arrSize, -1);
for (int i = 0; i < arrSize; i++) {
helper(arr1[i], arr2[i]);
}
}
int main(int argc, char* argv[]) {
using namespace std;
const clock_t startTime = clock();
arrayProcedure();
clock_t endTime = clock();
cout << endTime << endl;
double elapsedTime = msBetween(startTime, endTime);
cout << "\n\n" << elapsedTime << " milliseconds. ("
<< elapsedTime / 60000 << " minutes)\n";
}
The default stack size is 1 MB with Visual Studio.
https://msdn.microsoft.com/en-us/library/tdkhxaks.aspx
You can increase the stack size or use the new operator.
double *arr1 = new double[arrSize];
double *arr2 = new double[arrSize];
...
delete [] arr1;
delete [] arr2;
I want to generate pseudo-random numbers in C++, and the two likely options are the feature of C++11 and the Boost counterpart. They are used in essentially the same way, but the native one in my tests is roughly 4 times slower.
Is that due to design choices in the library, or am I missing some way of disabling debug code somewhere?
Update: Code is here, https://github.com/vbeffara/Simulations/blob/master/tests/test_prng.cpp and looks like this:
cerr << "boost::bernoulli_distribution ... \ttime = ";
s=0; t=time();
boost::bernoulli_distribution<> dist(.5);
boost::mt19937 boostengine;
for (int i=0; i<n; ++i) s += dist(boostengine);
cerr << time()-t << ", \tsum = " << s << endl;
cerr << "C++11 style ... \ttime = ";
s=0; t=time();
std::bernoulli_distribution dist2(.5);
std::mt19937_64 engine;
for (int i=0; i<n; ++i) s += dist2(engine);
cerr << time()-t << ", \tsum = " << s << endl;
(Using std::mt19937 instead of std::mt19937_64 makes it even slower on my system.)
That’s pretty scary.
Let’s have a look:
boost::bernoulli_distribution<>
if(_p == RealType(0))
return false;
else
return RealType(eng()-(eng.min)()) <= _p * RealType((eng.max)()-(eng.min)());
std::bernoulli_distribution
__detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng);
if ((__aurng() - __aurng.min()) < __p.p() * (__aurng.max() - __aurng.min()))
return true;
return false;
Both versions invoke the engine and check if the output lies in a portion of the range of values proportional to the given probability.
The big difference is, that the gcc version calls the functions of a helper class _Adaptor.
This class’ min and max functions return 0 and 1 respectively and operator() then calls std::generate_canonical with the given URNG to obtain a value between 0 and 1.
std::generate_canonical is a 20 line function with a loop – which will never iteratate more than once in this case, but it adds complexity.
Apart from that, boost uses the param_type only in the constructor of the distribution, but then saves _p as a double member, whereas gcc has a param_type member and has to “get” the value of it.
This all comes together and the compiler fails in optimizing.
Clang chokes even more on it.
If you hammer hard enough you can even get std::mt19937 and boost::mt19937 en par for gcc.
It would be nice to test libc++ too, maybe i’ll add that later.
tested versions: boost 1.55.0, libstdc++ headers of gcc 4.8.2
line numbers on request^^