I am trying to make a dynamically growing array which increases in size every time the user enters any integer other than 0. When 0 is pressed, it stops taking data from user and the rest of the code is executed.
I tried to implement the growing array through a do while loop but it keeps giving me garbage values in my array.
int main(){
int size = 1;
int* ptr;
int* ptr1;
int i = 0;
int inp;
ptr = new int[size];
do{
ptr1 = new int[size];
cin >> inp;
if (inp == 0)
break;
else{
*(ptr + i) = inp;
size++;
i++;
for (int j = 0; j < size; j++){
*(ptr1 + j) = *(ptr + j);
}
}
} while (1);
for (int k = 0; k < size; k++)
cout << *(ptr1 + k) << endl;
system("pause");
return 0;
}
When you exit the loop you have already reserved memory again. That is, you have put ptr1 pointing to a memory address of size integers that you have not yet initialized. Also note that when you write *(ptr + i) = inp; you are trying to write to memory that you have not allocated. This is because although you increment ptr1, you do not do the same with ptr.
Related
When debugging, I found that segmentation fault caused after copy from temp array (b) to original array (a), I don't know how to solve this, can you guys help me on that?
#include <iostream>
using namespace std;
int main() {
int n;
cout << "n = ";
cin >> n;
int *a = new int[n];
for (int i = 0; i < n; i++)
cin >> a[i];
cout << "\nNumber to remove: ";
int k;
cin >> k;
for (int i = 0; i < n; i++)
{
while (a[i] == k && i < n - 1)
{
int *b = new int[n]{0};
for (int j = 0; j < i; j++)
b[j] = a[j];
for (int j = i + 1; j < n; j++)
b[j - 1] = a[j];
a = NULL;
delete a;
n--;
int *a = new int[n];
for (int j = 0; j < n; j++)
a[j] = b[j];
}
}
cout << "Result: ";
for (int i = 0; i < n; i++)
cout << a[i] << " ";
}
The problem with this implementation lies here:
a = NULL;
delete a;
When you use the delete keyword you are telling the compiler to free the memory allocated by a new keyword, in this case you have a which is a pointer to the memory allocated by int *a = new int[n];. a at this point would probably be a 32bit address for example 0xbfebd5c0, i said probably because it depends on the architecture of the machine, however... after that you are setting a to NULL resulting in a being 0x0, at the next while condition check a is NULL and accessing 0x0 + i is not possible due to safety reasons imposed by the OS (no one gave you access to this location). The solution to your specific problem would be removing a = NULL; and delete a; as both these operations interfere with the while condition check.
I would suggest to take another approach at solving this problem since you really don't need to do this many dynamic allocations.
I am trying to create a program that prints out an array based on user input. The array needs to start from 0 and scale to the number enter by user. So if user inputs 5 the the array values will be [0][1][2][3][4][5]. For some reason my code just prints out 0.
#include <iostream>
using namespace std;
int main() {
cout << "Enter the value of n: ";
int n;
cin >> n;
int *arr1 = new int[n];
for(int i = 0; i < n; i ++){
arr1[i] = 0;
}
cout << *arr1 << endl;
delete [] arr1;
return 0;
}
There are few bugs in your code.
You expect the output to be [0][1][2][3][4][5] when the n = 5. Therefore your output has (n + 1) elements. So your array should also have (n + 1) elements.
int *arr1 = new int[n + 1];
In your code you assign 0 to each element in your array. But you expect the array to contain 0, 1, 2, .., n
for(int i = 0; i < n + 1; i++){
arr1[i] = i;
}
In your code, you only print the first element. *arr1 is same as arr1[0]. So another for loop is required to print the each element in your array.
for(int i = 0; i < n + 1; i++){
cout << "[" << arr1[i] << "]" << endl;
}
Then you will get the output [0][1][2][3][4][5] when the n = 5
Can not figure out why my recursion function does not work?
#include <iostream>
using namespace std;
int ReverseArray(int* A, int i, int j);
int main()
{
int j = 10;
int i = 0;
int *b = new int[j];
for (int i = 0; i <= 10; i++)
b[i] = i;
for (int i = 0; i <= 10; i++) //just to compare the old and new array
cout << b[i] << endl; //just to compare the
for(int i = 0; i <= j; i++)
cout << ReverseArray(b,i,j) << endl;
system("pause");
return 0;
}
int ReverseArray(int* A, int i, int j)
{
if (i <= j)
{
swap(A[i], A[j]);
ReverseArray(A, i + 1, j - 1);
}
return A[i];
This should return
10,9,8....
but it returns
10,0,9,1...
I don't get why its happening
You have a double loop, once here:
for(int i = 0; i <= j; i++)
cout << ReverseArray(b,i,j) << endl;
and once here:
ReverseArray(A, i + 1, j - 1);
Calling a function recursively is equivalent to looping over it. To reverse a list, you only need to loop over it once, and what you've done is the equivalent of a doubly-nested loop. So let's get rid of
for(int i = 0; i <= j; i++)
and change
cout << ReverseArray(b,i,j) << endl;
to just
ReverseArray(b,i,j);
Then you are only reversing b, nothing else. To print, just loop from 0 to 10 and print each element.
Also, unrelated, but keep in mind that the code as you have it right now touches memory that has not been allocated to the heap.
int *b = new int[j];
creates j (here, 10) ints, at the physical memory locations b, b + 1, b + 2, ..., b + 9. b[i] then gets the memory held at b + i, that is, it gets *(b + i). Several of your loops try to do things with b[10], and there has not been enough memory allocated for it. This will result in undefined behaviour (i.e. many different things can happen depending on your compiler and the state of your computer). With 'system("pause");' removed (which shouldn't affect code execution) on my machine, this gave me a memory allocation for that reason.
Solution here is to either have
int *b = new int[j+1];
or replace all your <= signs with <.
I have this function in order to expand the size of my char **array that I use in two other functions, which is why I'm passing it in by reference. I know I'm supposed to delete array at some point because it's dynamically allocated in this function, but I cant delete it until after I'm done using it in my code. However, valgrind still says memory is definitely lost in the line which contains array = new char *[cap2]. How should I go about deleting this?
void expand(int &size2, int &cap2, char **&array){
int i;
if(size2 ==1)
{
cap2 = size2;
cap2 = cap2*2;
array = new char*[cap2];
for(int n=0; n<cap2; n++)
{
array[n] = '\0';
}
}
else{
cap2 = cap2 *2;
char **temp;
temp = array;
array = new char*[cap2];
for(i =0; i<size2 ; ++i)
{
array[i] = temp[i];
}
for(int k = size2; k<cap2; k++)
{
array[k] = '\0';
}
}
return;
}
I've been getting heap corruption error on delete[] instruction. Project is worked on in VC++ 2008, its requirement (so please don't focus on that). Whole building process is working OK, but in run-time I get error: (prs_2013 is name of my project)
Windows has triggered a breakpoint in prs_2013.exe.
This may be due to a corruption of the heap, which indicates a bug in prs_2013.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while prs_2013.exe has focus.
The output window may have more diagnostic information.
This is code where error occurs, its just a fraction of whole project, but error is confined in this area:
// Function used for swapping row of matrix with new values
void Main::swap(double* matrix, double* row, unsigned index, unsigned size){
double temp = 0;
for(unsigned i = 0; i < size; i++){
temp = matrix[i*size + index];
matrix[i*size + index] = row[i];
row[i] = temp;
}
}
// Function that do some calculations, not really relevant for this problem
// but still used in code
double Main::determinat(double* matrix, unsigned size){
double ud = 0, du = 0;
for(unsigned j = 0; j < size; j++){
double ude = 1, due = 1;
for(unsigned i = 0; i < size; i++){
ude *= matrix[i*size + (i+j)%size];
due *= matrix[(size-i)*size + (i + j)%size];
}
ud += ude;
du += due;
}
return ud - du;
}
// Function in which error occurs
double* Main::get_x(double* matrix, unsigned size){
// error checking
if(size == 1){return NULL;}
double *x = new double[size];
x[0] = 1;
unsigned const temp_size = size-1;
double *temp = new double[temp_size * temp_size]; // temporary matrica
double *x0_coef = new double[temp_size]; // variable on which error occures
for(unsigned i = 0; i < temp_size; i++)
x0_coef[i] = matrix[i*size + 0] / s[0]; // s is class member, init in constructor s[0] != 0
for(unsigned i = 1; i < size; i++)
for(unsigned j = 1; j < size; j++)
if(i == j)
temp[(i-1)*size + j-1] = (matrix[i*size + j] - 1) / s[i];
else
temp[(i-1)*size + j-1] = matrix[i*size + j] / s[i];
double deltaS = determinat(temp, temp_size); // delta of system
for(unsigned i = 0; i < temp_size; i++){ // delta of vars
swap(temp, x0_coef, i, temp_size);
x[i+1] = determinat(temp, temp_size) / deltaS;
swap(temp, x0_coef, i, temp_size);
}
delete[] x0_coef; // place where error occures
delete[] temp;
return x;
}
But same thing happens if I switch delete[] x0_coef; with delete[] temp;, error occurs on temp;
As you can see in code I'm not using char, ie. making String so adding '\0' is useless because 0 is still valid value.
But now interesting part, I've tested swap function with this code:
#include <iostream>
using namespace std;
void swap(double* a, double* b, unsigned size){
double temp = 0;
for(unsigned i=0; i < size; i++){
temp = a[i];
a[i] = b[i];
b[i] = temp;
}
}
void main(){
double *a = new double[5],
*b = new double[5];
for(unsigned i=0; i < 5; i++){
a[i] = i;
b[i] = i*i;
}
swap(a, b, 5);
for(unsigned i=0; i < 5; i++)
std::cout << "a: " << a[i] << " b: " << b[i] << endl;
delete[] a;
delete[] b;
system("PAUSE");
}
And everything worked.
To be honest I'm at end of my wits, just spent 2-3 days trying to find out what is that I'm missing. But most of other topics are related on making char array, String, and general miss calculation of arrays length. And as is it shown in code I always carry arrays length to other functions.
I'm sure that there are better codes to do what I have to do, but this is solo-required project so I'm not looking in better functionality just to help me see what I'm doing wrong with arrays.
Your code corrupts memory when it writes into an out-of-bounds index of array temp. And when the heap is corrupted, anything can happen (like a crash on delete[] call).
Your temp array contains (size-1)*(size-1) items, while it is treated it as a size*(size-1) array inside the double loop: temp[(i-1)*size + j-1] = ... (because you multiply "the first index" by size).
I guess replacing it with temp[(i-1)*temp_size + j-1] will solve the problem.