Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
how to handle the exception caused in this case using try-catch block. please help . thanks
double **pDblArray = 0;
pDblArray = new double *[5000000];
for(int i=0; i<5000000; i++)
{
pDblArray [i] = new double [5000000];
}
cout << "Completed Allocated" << endl;
Assuming you have enough memory:
try {
std::vector<std::vector<double>> vec(5000000, std::vector<double>(5000000));
// …
} catch (std::bad_alloc const& e) {
// …
}
I don't know the name of the particular exception for memory allocation overrun. Look that up.
double **pDblArray = 0;
pDblArray = new double *[5000000];
try
{
for (int i = 0; i < 5000000; i++)
{
pDblArray [i] = new double [5000000];
}
}
catch (std::bad_alloc const &e)
{
cout << "Boom! " << endl;
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 months ago.
Improve this question
I'm struggling with removing the array from the memory.. it was allocated dynamically. I'd love some help, thanks!
void RemoveAllocationOfIntegerArray(int** arr, int size) {
for (int i = size - 1; i >= 0; i--) {
delete arr[i];
arr[i] = NULL;
}
delete[] arr;
arr = NULL;
}
First, you don't need these lines:
arr[i] = NULL;
// or
arr = NULL;
Next, you should delete arrays using delete[] operator. So, replace
delete arr[i];
with:
delete[] arr[i];
Another point is, you can free memory using delete or delete[] only if it is allocated with new or new[].
Lastly, You don't need to go backward when freeing. It is not necessary (except for some odd cases).
Example of using std::vector, or std::vectorstd::vector<int>
#include <format>
#include <vector>
#include <iostream>
void function_on_2d_data(std::vector<std::vector<int>>& values) // pass non const so you can modify values.
{
values[1][1] = 7;
}
void show_2d_data(const std::vector<std::vector<int>>& values) // pass const, show should not modify content
{
for (const auto& row : values)
{
for (const auto& value : row)
{
std::cout << value << " ";
}
std::cout << "\n";
}
}
// a function returning dynamically allocated 2d arrays (much more safe then int** with no size info);
std::vector<std::vector<int>> create_2d_data()
{
std::vector<std::vector<int>> values(4, std::vector<int>(3, 1)); // This does all the "new"-ing for you, and set values in each row to 1
return values;
}
int main()
{
// create a 2d datastructure containing 4 row and 3 columns;
std::vector<std::vector<int>> values = create_2d_data();
std::cout << std::format("values has {0} rows\n", values.size()); // see size information is returned too
function_on_2d_data(values);
show_2d_data(values);
return 0;
// values goes out of scope and it will do all the "delete"-ing for you
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 months ago.
Improve this question
I'm not sure why this is happening. Updated my original post to add in the suggestions made thank you everyone for your help!
The issue function was made by my professor. The function I am making is the board() function.
MY FUNCTION
TourBus& TourBus::board()
{
char passName[40];
int i = 0;
cout << "Boarding " << busSizeNumber << " Passengers: " << endl;
for (i = 0; i < busSizeNumber; i++)
{
cout << i + 1 << "/4- Passenger Name: ";
cin.getline(passName, 40,'\n');
ticket->issue(passName);
}
return *this;
}
MY PROFESSOR'S FUNCTION
TourTicket& TourTicket::issue(const char* passengerName) {
if (passengerName && passengerName[0]) {
copyName(passengerName);
m_ticketNumber = next_ticketNumber++;
}
return *this;
}
void TourTicket::copyName(const char* str) {
int i = 0;
for (i = 0; i < 40 && str[i]; m_name[i] = str[i], i++);
m_name[i] = 0;
}
This is a picture of the instructions for this function:
this is the picture of the error
the variables i am watching are all holding the string correctly however its just not copying it and throwing that error
In this line, the method declares a pointer but doesn't initialize it to point to anything:
char* passName;
... and then in this line you call getline() and pass in the uninitialized pointer as an argument:
cin.getline(passName, 20,'\n');
getline() will try to write some text into the buffer that passName is pointing to... but passName is uninitialized, so it is not pointing to any well-defined region of memory. Hence, the attempt to dereference it invokes undefined behavior, and you get a write-access error.
I think you'd get a result more in line with what you wanted if you changed the passName declaration to something like this:
char passName[20]; // allocates 20 bytes of stack space to hold chars in
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
29==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000478 at pc 0x0000003a5517 bp 0x7ffe2f5c2670 sp 0x7ffe2f5c2668
Here is my code:
class Solution {
public:
vector summaryRanges(vector& nums) {
if(nums.size() == 0)
return {};
if(nums.size() == 1)
return {to_string(nums[0])};
vector<string> ans{};
int i=0,j=1,initial=nums[0];
if(nums.empty()||nums.size()==0)
return ans;
while(j<=nums.size())
{
if(i<nums.size())
{
if(nums[i]+1==nums[j])
{
i++;
j++;
}
else
{
string str3;
if(initial!=nums[i])
{
string str = to_string(initial);
string str1= to_string(nums[i]);
string str2 = "->";
str3=str+str2+str1;
}
else
{
str3 = to_string(initial);
}
ans.push_back(str3);
initial=nums[j];
i=j;
j++;
}
}
else
{
string str = to_string(initial);
ans.push_back(str);
}
}
return ans;
}
};
I think you are accessing an index out of vector size . Index j is probably going out of bounds .
while(j< = nums.size())
and
nums[j]
This
while(j<=nums.size())
and these
if(nums[i]+1==nums[j])
...
initial=nums[j];
look very suspicious. If j == nums.size() then nums[j] is an out of bounds error on num. Maybe you meant this?
while(j<nums.size())
(I.e. the same as you have with the i variable).
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am having a very tough time understanding exception handling after watching online tutorials and reading up on it. I am trying to pass test driven development, and I can't. What I have come up with so far is this. I am supposed to use this struct
struct ArrayException
{
ArrayException(string newMessage = "error") :message(newMessage)
{
}
string message;
};
The first try.
int sum(int* theArray, unsigned int arraySize)
{
try
{
if (theArray = NULL)
{
throw ArrayException("NULL ARRAY REFERENCE");
}
}
catch (int* param)
{
cout << "you can't have " << param << " as an array size";
}
int sum = 0;
for (int i = 1; i < arraySize; i++)
{
sum += theArray[i];
}
return sum;
}
I also tried doing it this way.
int sum(int* theArray, unsigned int arraySize)
{
if (theArray = NULL)
{
throw ArrayException("NULL ARRAY REFERENCE");
}
else
{
int sum = 0;
for (int i = 1; i < arraySize; i++)
{
sum += theArray[i];
}
return sum;
}
}
While the post does not specifically mention it, I take it that the question is why exception is not caught? The answer is simple - because exception thrown is of type ArrayException, and catch is done with the type int*.
The best way to get a grip on this stuff is as πάντα ῥεῖ recommended: get a good book. Here's a good place to start selecting books: The Definitive C++ Book Guide and List
The rest is a code block with comments where I figured they were needed.
#include <iostream>
// removed the using namespace std;
struct ArrayException
{
ArrayException(std::string newMessage = "error") :
message(newMessage)
{
}
std::string message;
};
int sum(int* theArray, size_t arraySize) // change made here:
// size_t better suited than unsigned int for indexes
{
//throw std::out_of_range("BOOM!"); //uncomment to trigger a std::exception
//throw 42; // uncomment to trigger the unknown exception
if (theArray == NULL)
{
throw ArrayException("NULL ARRAY REFERENCE"); //perfect!
}
else
{
int sum = 0;
for (size_t i = 0; i < arraySize; i++) // changes made here:
// size_t not int to get rid of signed/unsigned conflict
// starting with array index 0, not 1
{
sum += theArray[i];
}
return sum;
}
}
int main()
{
try
{
sum (NULL, 10); // NULL address to force the exception
}
catch (ArrayException & param) // catch the custom exception
// catch by reference where possible
{
std::cout << "This bad stuff happened: " << param.message << std::endl;
}
// extra stuff to show what can also be done
catch (std::exception & stdexcpt) // catch any standard exceptions and
// print their message
{
std::cout << "Standard exception thrown: " << stdexcpt.what() << std::endl;
}
catch (...) // catch anything else that was thrown and doesn't
// correspond to any expectation
{
std::cout << "No idea what happened." << std::endl;
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've started C++ not too long ago, and I have problems understanding why I can'T seem to be able to create two functions outside my main. When I only have 1, all is good, the second I add the second one, which is the Far one, tell me to put a ; after my cel function declaration...
// Lab03.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
int main()
{
double celcius(int);
double far(int);
std::cout<<"DEGREE DE FAR A CEL\n";
for (int i=32; i<213; i++)
{
std::cout.precision(3);
std::cout<<i<<"F = " <<celcius(i)<<"C ";
if ((i+1)%4==0)
{
std::cout<<"\n";
}
std::cout<<"\n\n\nDEGREE DE CEL A FAR\n";
for (int i=0; i<101; i++)
{
std::cout.precision(3);
std::cout<<i<<"C = " <<far(i)<<"C ";
if ((i+1)%4==0)
{
std::cout<<"\n";
}
}
_gettch();
return 0;
}
double celcius(int n)
{
double endcel;
endcel= (n-32.0)*(5.0/9.0);
return endcel;
}
double far(int o)
{
double endfar=(o*(9/5))+32;
return endfar;
}
It looks like you're missing an end } to close your main function just prior to the celcius function.
Proper code indentation will help you find problems like this in the future.
// Lab03.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
int main() {
double celcius(int);
double far(int);
std::cout<<"DEGREE DE FAR A CEL\n";
for (int i=32; i<213; i++) {
std::cout.precision(3);
std::cout<<i<<"F = " <<celcius(i)<<"C ";
if ((i+1)%4==0) {
std::cout<<"\n";
}
std::cout<<"\n\n\nDEGREE DE CEL A FAR\n";
for (int i=0; i<101; i++) {
std::cout.precision(3);
std::cout<<i<<"C = " <<far(i)<<"C ";
if ((i+1)%4==0) {
std::cout<<"\n";
}
}
_gettch();
return 0;
}
}
double celcius(int n) {
double endcel;
endcel= (n-32.0)*(5.0/9.0);
return endcel;
}
double far(int o) {
double endfar=(o*(9/5))+32;
return endfar;
}