I was doing a test and the online test engine showing segmentation error, which is confusing because with no further details, and I checked the pointer no NULL and they work pretty fine, but don't how array here works. Because when debugging, everything is fine, until I try to cout/print out the array. it's reporting a is crushed here and break. I can do nothing here if it break, and I hit break or continue. if I continue, it runs just fine. so I was really confused.
My computer is windows 7, I run code in visual studio 2010 c++.
Debugging is not that clear to solve the problem, and I am learning c++ not very efficient.
Solve with Array need dynamic allocation.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
void reverseArray(int size, int num[]) {
if(size>1) {
int *p = &num[size-1];
int *f = num;
for(int i = 0;i < size/2; i++){
swap(*p, *f);
p--;
f++;
}
}
}
int main() {
int len;
int a[len];/This is the bug, can't use uninitialized var assign array/
cin >> len;
for(int i = 0; i < len; i++){
cin >> a[i];
}
reverseArray(len, a);
for(int i = 0; i < len; i++){
cout << a[i] << " ";
}
return 0;
}
This has something to with dynamic allocation, when I work in java, I create a new array.
I have to
int[] newArray = {2,4,1,2,3};
or
int[] newArray = new int[] {2,4,1,2,3};
Finally, this problem is solved, which makes me very happy.
Reading and learning is very important, coding is also important.
Thanks all,
And using vector instead of using array.
It would be easier.
#include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
int main() {
int a;
int len;
vector<int> myvector;
cin >> len;
for(int i = 0; i < len; i++){
cin >> a;
myvector.push_back(a);
}
reverse(myvector.begin(), myvector.end());
for(int i = 0; i < len; i++){
cout << myvector[i] << " ";
}
return 0;
}
Using Array again(I doubt the following code):
#include<iostream>
//#include<cstdlib>
using namespace std;
void reverseArray(int size, int nums[]){
if(size > 1){
int *p = &nums[size-1];
int *q = nums;
for(int i = 0; i< size/2; i++){
swap(*p, *q);
p--;
q++;
}
}
}
int main(){
int len;
cin >> len;
int *a = new int[len];//a point to the first ele.
for(int i = 0; i< len; i++){
cin >> a[i];
}
reverseArray(len, a);
for(int i = 0; i < len; i++){
cout << a[i] << " ";
}
delete [] a;
return 0;
}
It worked perfect on my laptop, which is confusing because a is pointer, but I use it like an array. It shouldn't be working......
Final Array version:
http://ideone.com/ZMsD35
Done perfectly.
#include<iostream>
using namespace std;
int main(){
int len;
cin >> len;
int *a = new int[len];
for(int i = 0; i< len; i++){
cin >> a[i];
}
reverse(a, a+len);
for(int i = 0; i< len; i++){
cout << a[i];
}
delete [] a;
system("pause");
return 0;
}
The most likely reason for a segfault is the input. When the testing software passes len of size sufficient to overflow the automatic storage area, your program crashes on this line:
int a[len];
The exact value of len is system-dependent, but an input of 1,000,000 should do it on most common systems.
The fix is really straightforward - replace the declaration with
int a* = new int[len];
This will place the data in dynamic memory, rather than the automatic memory. It will also make your program standard-compliant, because variable-length arrays in C++ are an extension to standards.
Don't forget to delete a once you are done to avoid memory leak:
delete[] a;
Related
I want to create a function which generates an array(filled with random numbers) of the size I give as an input and the function returns the address of the first element of the generated array. I wrote the code as best as possible without any errors or warning. But at the runtime, the program crashes. I try to debug it but the debugger also froze and do nothing. I think the problem is in returning the pointer. Please help.
#include<iostream>
#include<cstdlib>
using namespace std;
int** the_gen(int num)
{
srand(1000);
int *ptr= new int(num);
int** const dptr=&ptr;
for(int i=0;i<num;i++)
{
*ptr= rand();
ptr++;
}
return dptr;
}
int main()
{
cout<<"Size of array:"<<endl;
int size_of_array;
cin>>size_of_array;
int **a;
a=the_gen(size_of_array);
for(int i=0;i<size_of_array;i++)
{
cout<<**a<<",";
a++;
}
}
you were using int** unnecessarily. only need to use that if you're creating an array of int pointers or a 2d array of int's:
the following code does what you're after i think:
#include<iostream>
#include<cstdlib>
using namespace std;
int* the_gen(int num)
{
srand(1000);
//edit
int *ptr = new int[num];
int* const dptr = ptr;
for (int i = 0; i < num; i++)
{
*ptr = rand();
ptr++;
}
return dptr;
}
int main()
{
cout << "Size of array:" << endl;
int size_of_array;
cin >> size_of_array;
int *a;
a = the_gen(size_of_array);
for (int i = 0; i < size_of_array; i++)
{
cout << *a << ",";
a++;
}
}
I think returning pointer is always bad idea, we should take memory pointers as a parameter as the follow
void the_gen(int num, int** arry)
{
srand(1000);
int *ptr = new int[num];
*arry = ptr;
for (int i = 0; i < num; i++)
{
ptr[i] = rand();
}
}
int main()
{
cout << "Size of array:" << endl;
int size_of_array;
cin >> size_of_array;
int *a;
the_gen(size_of_array, &a);
for (int i = 0; i < size_of_array; i++)
{
cout << a[i] << ",";
}
}
My code below outputs 0, the value of max_explode, before even reading in my input. Why is this happening?
#include <iostream>
#include <vector>
#include <algorithm>
#define MAX 100
using namespace std;
int N,cnt=0;
vector<int> arr;
bool seen[MAX+1];
int main()
{
for (int i = 0; i < N; i++) seen[i]=false;
int max_explode=0;
for (int i = 0; i < N; i++)
{
int cow;
cin >> cow;
arr.push_back(cow);
}
sort(arr.begin(),arr.end());
cout << max_explode << "\n";
return 0;
}
You read input in a loop:
for (int i = 0; i < N; i++)
{
int cow;
cin >> cow;
arr.push_back(cow);
}
However, N is never explicitly initialized. Since it's a global variable, it's automatically initialized to 0, and your loop never runs.
There's a small issue in your 7th line to be specific. You have defined the variable N but haven't initialized a value to it.
I am currently creating a program that simulates a Galton board in C++. I understand how to create a pointer, create an array of pointers, and point each one at another array of ints. My problem is occuring when i try to descruct my pointer array, its telling me:
"Debug Error!
HEAP CORRUPTION DETECTED: after Normal block (#927) at 0x0115E978.
CRT detected that the application wrote to memory after end of heap buffer."
I've been banging my head against the wall with this one, as it seems all the examples I can find online have this exact approach. I even rewrote my program into a class to make it more simple. The program runs and does exactly what it's supposed to until the ob1 starts to descruct, which is when the program pukes. I'm stuck.
Here is my code:
#include <iostream>
#include <string>
#include <algorithm>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
class foo
{
public:
foo();
foo(int);
~foo();
void allocateSpace();
void runGame();
void printResults();
private:
int bins;
int** p;
};
foo::foo()
{
this->bins = 0;
}
foo::foo(int bins)
{
this->bins = bins;
this->p = new int*[bins]; //setting p to array of pointers
}
foo::~foo()
{
for (int i = 0; i < bins; i++)
{
delete[] this->p[i];
}
delete[] p;
}
void foo::allocateSpace()
{
for (int i = 0; i < bins; i++)
{
this->p[i] = new int[i]; //creatung an int array of size i at each pointer array cell
for (int j = 0; j <= i; j++)
{
this->p[i][j] = 0;
}
}
}
void foo::runGame()
{
const int numOfRuns = 1000;
for (int i = 0; i < numOfRuns; i++)
{
this->p[0][0]++; //each ball hits the first peg, so always increment it before anything else
int j = 0; //setting j = 0 sets it to the left
for (int i = 1; i < bins; i++)
{
int rando = rand() % 2;
if (rando == 1) //move right
{
j++;
}
this->p[i][j]++;
}
}
}
void foo::printResults()
{
for (int i = 0; i < bins; i++)
{
for (int j = 0; j <= i; j++)
{
cout << setw(5) << this->p[i][j];
}
cout << endl;
}
}
int main()
{
srand(time(0));
int numOfBins;
cout << "Enter the number of bins: ";
cin >> numOfBins;
cout << endl;
foo ob1(numOfBins);
for (int i = 0; i < 50; i++)
{
ob1.allocateSpace();
ob1.runGame();
ob1.printResults();
}
system("pause");
return 0;
}
Any help would be much appreciated.
In allocateSpace, you write beyond the allocated object. This corrupts your heap.
this->p[i] = new int[i];
for (int j = 0; j <= i; j++)
{
this->p[i][j] = 0;
}
printResults has a similar problem: You read beyond the allocated object.
Then, in runGame, you attempt to increment a 0 sized object.
this->p[0][0]++;
The fix:
It seems you need to increase your allocation by 1.
this->p[i] = new int[i+1];
This will avoid the heap corruption issue. You still have a memory leak issue, because you allocate new memory on top of your existing memory on each iteration in main().
Your code would be safer if you adopted the use of vector<> instead of managing dynamically allocated arrays.
#include <iostream>
using namespace std;
char problem5(char alc[], char a, int *n);
int main() {
char aloc1[]={ 'g','g','c','g','a','g','g','g','t','g'};
int size=sizeof(aloc1)/sizeof(aloc1[0]);
cout << aloc1 << endl;
int nalc = problem5(aloc1, 'g' ,&size);
cout << nalc << endl;
return 0;
}
char problem5(char alc[], char c, int *n){
int a = 0;
for(int i = 0; i < n; i++){
if(alc[0]!=c){
a++;
}
}
int nalc[a];
int b=0;
for(int j = 0; j < n; j++){
if(alc[0]!=c){
nalc[b]=alc[j];
b++;
}
}
*n=&a;
return nalc;
}
why do I keep having errors at the two for loops of the problem5?
it says something like comparison between pointer and int.
how can i fix that while the argument n remains pointer.
Use *n to access the value pointed by n:
for(int i = 0; i < *n; i++){
And to change the value pointed by n to be equal to a:
*n = a;
You can't have an address in a for-loop. Try dereferencing the pointer. and also post your exact error please.
I'm a beginner, so I'm sorry if this is really dumb question/problem.
The assignment that I have is printing out a dynamic array from an input file. I tried googling it and I found some similar problems... but the answers were all like "use vectors" etc but we haven't learned those yet. It's also said that a function must be used. This is what I came up with:
#include <iostream>
#include <fstream> //file input
using namespace std;
int *out(int *arr, int siz){
arr = new int[siz];
for (int i = 0; i < siz; i++) {
cout << arr [i] << " ";
}
return arr; //this should print out the array later???
}
int main(){
int siz;
int *arr;
ifstream inf ("input.txt");
inf >> siz; //
for (int i = 0; i < siz; i++) {
inf >> arr[i];
}
inf.close();
cout << "This array contains following elements: ";
*arr = *out(arr, siz) ;
delete[] arr;
return 0;}
So, it doesn't give any errors with Dev-C++ but when I try to run it, it crashes. I tried debugging it and then it gave me "segmentation error" or something like that. Then of course, I googled it and there must be something wrong with the pointers, right? Could you help me out? Thanks.
You are trying to access arr, when arr has not been allocated or initialized to a valid array. Your main needs to allocate arr before using arr to populate elements:
So, here's the changed version:
#include <iostream>
#include <fstream> //file input
using namespace std;
void out(int *arr, int siz){
for (int i = 0; i < siz; i++) {
cout << arr [i] << " ";
}
}
int main(){
int siz;
int *arr;
ifstream inf ("input.txt");
inf >> siz;
arr = new int[siz]; // added
for (int i = 0; i < siz; i++) {
inf >> arr[i];
}
inf.close();
cout << "This array contains following elements: ";
out(arr, siz);
delete[] arr;
return 0;
}
arr is an uninitialized pointer.
Do arr = new int[size]; before you read data into arr.
You haven't allocated memory to the array, which you'd likely need to do with malloc. Once you've read in the size of the array, allocate the memory.
inf >> siz;
arr = malloc(siz * sizeof(*int));
//Rest of program
//delete[] arr; <- you use this with the new keyword
free(arr); //Use 'free' with malloc
return 0;
I think what you want might be sth like this
#include <iostream>
#include <fstream>
int main(){
int siz(0);
std::ifstream inf ("input.txt");//Assume that the input file and this file are in the same folder
inf >> siz; //Assume that the first number in input file is the size of array
int *arr=new int[siz];
for (int i = 0; (siz-i)&&inf ; ++i) {
inf >> arr[i];
}
inf.close();
std::cout << "This array contains following elements: ";
for (int i = 0; siz -i ; ++i ) {
std::cout << arr [i] << " ";
}
delete[] arr;
return 0;
}