Creating a global dynamically-allocted array - c++

I am new to C/C++ and I had a question about dynamically allocating arrays. Can you not make a global dynamically allocated array? What if I wanted arr to be used by multiple functions? Would I have to pass arr to every function? Basically I guess I am still confused on the concept of dynamically allocated arrays and how I could create an array that can be used by a few functions.
The following produces : error: ‘arr’ does not name a type, but I am not sure exactly why.
#include <iostream>
using namespace std;
int * arr = NULL;
arr = new int [10];
int main() {
arr[0] = 1;
return 0;
}

That's invalid for the same reason that this is invalid
#include <iostream>
using namespace std;
int a = 0;
a = 2;
int main() {
}
You can't run statements outside of a function, only initializers. As a result, this works:
#include <iostream>
using namespace std;
int *arr = new int[10];
int main() {
arr[0] = 1;
return 0;
}

You don't even have to make the array dynamic, you can just put the array in static memory outside main, and it will live as long as the program.
#include <iostream>
int arr[10];
int main() {
arr[0] = 1;
return 0;
}

int* arr = new int[10];
or (since you are allocate a constant size array):
int arr[10];

You can't have "code" outside of a function. You need to put the call to new inside a function - you only have one in your code: main, but as long as it is a function that is executed before you access the array, it's fine.
You can also, as the comment says, do int *arr = new int[10]; - as long as it's part of the initialization, and not on a separate line.

Related

Heap Corruption Detected in Dynamic Array c++?

I was learning how to use the delete operator for dynamic arrays and i ran into some really strange problem. I tried two approach to write the same code - one worked but the other dint work. So, here is the code i tried
Method 1:-
#include <iostream>
using namespace std;
int main()
{
int *p = new int(2);
for(int i =0; i<2;i++)
{
cin>>p[i];
}
for(int i=0; i<2;i++)
{
cout<<p[i];
}
delete[] p;
system("pause");
}
//Error message - Heap Corruption detected. Can someone please explain me the reason of the error?
Method 2:- Using TypeDef
#include <iostream>
using namespace std;
typedef int arr[2];
int main()
{
int *p = new arr;
for(int i =0; i<2;i++)
{
cin>>p[i];
}
for(int i=0; i<2;i++)
{
cout<<p[i];
}
delete[] p;
system("pause");
}
//The above method works perfectly with no error. I am totally confused!!
First case: you are only creating one int and assigning it the value of 2.
Then you treat it as an array with two elements. That's undefined behaviour. You need to use new int[2]. Your delete[] syntax is correct.
Your second example is far too obfuscated.
You're calling the constructor of one int with the value of 2 not allocating two ints.
Use square brackets instead.
int *p = new int[ 2 ];
new int(2) allocates one int that has the value 2.
new int[2] allocates an array of two ints, with indeterminate values.
in your first example you have:
int *p = new int(2);
which is initializing 1 pointer to the value of 2 rather than in your second example when you have a
new int[2];
where you're actually making 2 pointers.

Returning a pointer to an array in C++ [duplicate]

May I have any access to a local variable in a different function? If so, how?
void replaceNumberAndPrint(int array[3]) {
printf("%i\n", array[1]);
printf("%i\n", array[1]);
}
int * getArray() {
int myArray[3] = {4, 65, 23};
return myArray;
}
int main() {
replaceNumberAndPrint(getArray());
}
The output of the piece of code above:
65
4202656
What am I doing wrong? What does the "4202656" mean?
Do I have to copy the whole array in the replaceNumberAndPrint() function to be able to access it more than the first time?
myArray is a local variable and as thus the pointer is only valid until the end of its scope (which is in this case the containing function getArray) is left. If you access it later you get undefined behavior.
In practice what happens is that the call to printf overwrites the part of the stack used by myArray and it then contains some other data.
To fix your code you need to either declare the array in a scope that lives long enough (the main function in your example) or allocate it on the heap. If you allocate it on the heap you need to free it either manually, or in C++ using RAII.
One alternative I missed (probably even the best one here, provided the array is not too big) is to wrap your array into a struct and thus make it a value type. Then returning it creates a copy which survives the function return. See tp1's answer for details on this.
You can't access a local variable once it goes out of scope. This is what it means to be a local variable.
When you are accessing the array in the replaceNumberAndPrint function the result is undefined. The fact it appears to work first time is just a fortunate coincidence. Probably the memory location you are pointing to is unallocated on the stack and is still correctly set for the first call, but the call to printf then overwrites this by pushing values onto the stack during its operation which is why the second call to printf displays something different.
You need to store the array data on the heap and pass a pointer, or in a variable that remains in scope (e.g. a global or something scoped within the main function).
Try something like that. The way you do it "kills" myArray cause if it locally defined.
#include <stdio.h>
#include <stdlib.h>
void replaceNumberAndPrint(int * array) {
printf("%i\n", array[0]);
printf("%i\n", array[1]);
printf("%i\n" , array[2]);
free(array);
}
int * getArray() {
int * myArray = malloc(sizeof(int) * 3);
myArray[0] = 4;
myArray[1] = 64;
myArray[2] = 23;
//{4, 65, 23};
return myArray;
}
int main() {
replaceNumberAndPrint(getArray());
}
More : http://www.cplusplus.com/reference/clibrary/cstdlib/malloc/
Edit: As Comments correctly pointed out: A better way to do it would be that :
#include <stdio.h>
#include <stdlib.h>
void replaceNumberAndPrint(int * array) {
if(!array)
return;
printf("%i\n", array[0]);
printf("%i\n", array[1]);
printf("%i\n" , array[2]);
}
int * createArray() {
int * myArray = malloc(sizeof(int) * 3);
if(!myArray)
return 0;
myArray[0] = 4;
myArray[1] = 64;
myArray[2] = 23;
return myArray;
}
int main() {
int * array = createArray();
if(array)
{
replaceNumberAndPrint(array);
free(array);
}
return 0;
}
myArray goes out of scope as soon as you leave getArray. You need to allocate space for it on the heap instead.
Your code invokes Undefined Behaviour because myArray goes out of scope as soon as getArray() returns and any attempt to use (dereference) the dangling pointer is UB.
Local variables go out of scope upon return, so you can't return a pointer to a local variable.
You need to allocate it dynamically (on the heap), using malloc or new. Example:
int *create_array(void) {
int *array = malloc(3 * sizeof(int));
assert(array != NULL);
array[0] = 4;
array[1] = 65;
array[2] = 23;
return array;
}
void destroy_array(int *array) {
free(array);
}
int main(int argc, char **argv) {
int *array = create_array();
for (size_t i = 0; i < 3; ++i)
printf("%d\n", array[i]);
destroy_array(array);
return 0;
}
Alternatively, you can declare the array as static, keeping in mind the semantics are different. Example:
int *get_array(void) {
static int array[] = { 4, 65, 23 };
return array;
}
int main(int argc, char **argv) {
int *array = get_array();
for (size_t i = 0; i < 3; ++i)
printf("%d\n", array[i]);
return 0;
}
If you don't know what static means, read this question & answer.
Right way to do this is as follows:
struct Arr {
int array[3];
};
Arr get_array() {
Arr a;
a.array[0] = 4;
a.array[1] = 65;
a.array[2] = 23;
return a;
}
int main(int argc, char **argv) {
Arr a = get_array();
for(size_t i=0; i<3; i++)
printf("%d\n", a.array[i]);
return 0;
}
To understand why you need to do this, you need to know how sizeof(array) works. C (and thus c++) tries hard to avoid copying the array, and you need the struct to go past that. Why copying is needed is because of scopes -- the get_array() function's scope disappears and every value still needed from that scope will need to be copied to calling scope.
C++ solution:
"May I have any access to a local variable in a different function? If so, how?"
The answer is no, not after the function has ended. Local variables are destroyed at that point.
In C++ the way to deal with returning arrays is to manage them in a container like a std::array (fixed size) or a std::vector (dynamic size).
Eg:
void replaceNumberAndPrint(const std::array<int, 3>& array) {
printf("%i\n", array[0]);
printf("%i\n", array[1]);
printf("%i\n", array[2]);
}
std::array<int, 3> getArray() {
std::array<int, 3> myArray = {4, 65, 23};
return myArray;
}
In the second function the returned value is optimized by the compiler so you don't pay the price of actually copying the array.
In this code you have used pointer to local objects but when a function returns all local variables goes out of scope. If you will allocate memory (using malloc() function for allocation) then no data will be lost or overwrite.
int* getArray(int size) {
int *myArray = (int*)malloc(size*sizeof(int));
myArray[0] = 4;
myArray[1] = 65;
myArray[2] = 23;
return myArray;
}
int main() {
int i;
int *vector = getArray(3);
for(i=0;i<3;i++)
{
printf("%i\n",vector[i]);
}
getch();
return 0;
}
This code will print all the array elements and no overwritten will be happened.
Static ..or.. Global within your .c will do the trick ;)
However the entire time the program will occupy those 3 bytes BUT you avoid doing malloc on simple things like this (malloc recommended for big arrays)
On the other hand if the outside function modify the pointer, then the internal 'myArray' will be modified cause it points to it, that's it
int myArray[3];
int * getArray() {
myArray[0] = 4;
myArray[1] = 65;
myArray[2] = 23;
return myArray;
}

Array and Dynamically Allocated Memory [duplicate]

May I have any access to a local variable in a different function? If so, how?
void replaceNumberAndPrint(int array[3]) {
printf("%i\n", array[1]);
printf("%i\n", array[1]);
}
int * getArray() {
int myArray[3] = {4, 65, 23};
return myArray;
}
int main() {
replaceNumberAndPrint(getArray());
}
The output of the piece of code above:
65
4202656
What am I doing wrong? What does the "4202656" mean?
Do I have to copy the whole array in the replaceNumberAndPrint() function to be able to access it more than the first time?
myArray is a local variable and as thus the pointer is only valid until the end of its scope (which is in this case the containing function getArray) is left. If you access it later you get undefined behavior.
In practice what happens is that the call to printf overwrites the part of the stack used by myArray and it then contains some other data.
To fix your code you need to either declare the array in a scope that lives long enough (the main function in your example) or allocate it on the heap. If you allocate it on the heap you need to free it either manually, or in C++ using RAII.
One alternative I missed (probably even the best one here, provided the array is not too big) is to wrap your array into a struct and thus make it a value type. Then returning it creates a copy which survives the function return. See tp1's answer for details on this.
You can't access a local variable once it goes out of scope. This is what it means to be a local variable.
When you are accessing the array in the replaceNumberAndPrint function the result is undefined. The fact it appears to work first time is just a fortunate coincidence. Probably the memory location you are pointing to is unallocated on the stack and is still correctly set for the first call, but the call to printf then overwrites this by pushing values onto the stack during its operation which is why the second call to printf displays something different.
You need to store the array data on the heap and pass a pointer, or in a variable that remains in scope (e.g. a global or something scoped within the main function).
Try something like that. The way you do it "kills" myArray cause if it locally defined.
#include <stdio.h>
#include <stdlib.h>
void replaceNumberAndPrint(int * array) {
printf("%i\n", array[0]);
printf("%i\n", array[1]);
printf("%i\n" , array[2]);
free(array);
}
int * getArray() {
int * myArray = malloc(sizeof(int) * 3);
myArray[0] = 4;
myArray[1] = 64;
myArray[2] = 23;
//{4, 65, 23};
return myArray;
}
int main() {
replaceNumberAndPrint(getArray());
}
More : http://www.cplusplus.com/reference/clibrary/cstdlib/malloc/
Edit: As Comments correctly pointed out: A better way to do it would be that :
#include <stdio.h>
#include <stdlib.h>
void replaceNumberAndPrint(int * array) {
if(!array)
return;
printf("%i\n", array[0]);
printf("%i\n", array[1]);
printf("%i\n" , array[2]);
}
int * createArray() {
int * myArray = malloc(sizeof(int) * 3);
if(!myArray)
return 0;
myArray[0] = 4;
myArray[1] = 64;
myArray[2] = 23;
return myArray;
}
int main() {
int * array = createArray();
if(array)
{
replaceNumberAndPrint(array);
free(array);
}
return 0;
}
myArray goes out of scope as soon as you leave getArray. You need to allocate space for it on the heap instead.
Your code invokes Undefined Behaviour because myArray goes out of scope as soon as getArray() returns and any attempt to use (dereference) the dangling pointer is UB.
Local variables go out of scope upon return, so you can't return a pointer to a local variable.
You need to allocate it dynamically (on the heap), using malloc or new. Example:
int *create_array(void) {
int *array = malloc(3 * sizeof(int));
assert(array != NULL);
array[0] = 4;
array[1] = 65;
array[2] = 23;
return array;
}
void destroy_array(int *array) {
free(array);
}
int main(int argc, char **argv) {
int *array = create_array();
for (size_t i = 0; i < 3; ++i)
printf("%d\n", array[i]);
destroy_array(array);
return 0;
}
Alternatively, you can declare the array as static, keeping in mind the semantics are different. Example:
int *get_array(void) {
static int array[] = { 4, 65, 23 };
return array;
}
int main(int argc, char **argv) {
int *array = get_array();
for (size_t i = 0; i < 3; ++i)
printf("%d\n", array[i]);
return 0;
}
If you don't know what static means, read this question & answer.
Right way to do this is as follows:
struct Arr {
int array[3];
};
Arr get_array() {
Arr a;
a.array[0] = 4;
a.array[1] = 65;
a.array[2] = 23;
return a;
}
int main(int argc, char **argv) {
Arr a = get_array();
for(size_t i=0; i<3; i++)
printf("%d\n", a.array[i]);
return 0;
}
To understand why you need to do this, you need to know how sizeof(array) works. C (and thus c++) tries hard to avoid copying the array, and you need the struct to go past that. Why copying is needed is because of scopes -- the get_array() function's scope disappears and every value still needed from that scope will need to be copied to calling scope.
C++ solution:
"May I have any access to a local variable in a different function? If so, how?"
The answer is no, not after the function has ended. Local variables are destroyed at that point.
In C++ the way to deal with returning arrays is to manage them in a container like a std::array (fixed size) or a std::vector (dynamic size).
Eg:
void replaceNumberAndPrint(const std::array<int, 3>& array) {
printf("%i\n", array[0]);
printf("%i\n", array[1]);
printf("%i\n", array[2]);
}
std::array<int, 3> getArray() {
std::array<int, 3> myArray = {4, 65, 23};
return myArray;
}
In the second function the returned value is optimized by the compiler so you don't pay the price of actually copying the array.
In this code you have used pointer to local objects but when a function returns all local variables goes out of scope. If you will allocate memory (using malloc() function for allocation) then no data will be lost or overwrite.
int* getArray(int size) {
int *myArray = (int*)malloc(size*sizeof(int));
myArray[0] = 4;
myArray[1] = 65;
myArray[2] = 23;
return myArray;
}
int main() {
int i;
int *vector = getArray(3);
for(i=0;i<3;i++)
{
printf("%i\n",vector[i]);
}
getch();
return 0;
}
This code will print all the array elements and no overwritten will be happened.
Static ..or.. Global within your .c will do the trick ;)
However the entire time the program will occupy those 3 bytes BUT you avoid doing malloc on simple things like this (malloc recommended for big arrays)
On the other hand if the outside function modify the pointer, then the internal 'myArray' will be modified cause it points to it, that's it
int myArray[3];
int * getArray() {
myArray[0] = 4;
myArray[1] = 65;
myArray[2] = 23;
return myArray;
}

Make array in cpp

I am trying to make a new array in my project
the code is:
#include <iostream>
using namespace std;
void makeArray( int *& arrayPtr, int size );
int main( )
{
int * arrPtr;
int size =10;
makeArray( arrPtr, size );
for(int j=0;j<size;j++)
{
cout<<arrPtr[j]<<endl;
}
}
void makeArray( int *& arrayPtr, int size )
{
int arr[size-1];
for(int i=0;i<size;i++)
{
arr[i]=0;
}
*&arrayPtr=*&arr;
}
According to the requirements i need to use the above "makeArray" method inorder to make the array.
When i run the code the output is garbage values not zero.....
any help will be appreciated
thank you
The way you are creating the array is on the stack, which means that it will not exist after the makeArray function finishes.
You will need to allocate the array on the heap.
So:
int arr[size-1];
should be:
int *arr = new int[size-1];
Also, I think you mean to do this in makeArray():
arrayPtr = arr;
Instead of:
*&arrayPtr=*&arr;
Which compiles but is more complex and is functionally the same thing in this context.
But you may prefer just returning an int* instead of taking a reference to the pointer.
Then when you are done using the array in main(), and set it to NULL just in case you accidentally use it again, like this:
for(int j=0;j<size;j++)
{
cout<<arrPtr[j]<<endl;
}
delete [] arrPtr;
arrPtr = NULL;
Why are you declaring a parameter as 'int *& arrayPtr'? Do you just need a pointer to an array? You should use 'int *arrayPtr' instead.
To answer your question, the problem is that you are declaring an array in the function makeArray's stack. Upon the completion of a function, that function's stack is destroyed, so you're passing the address of junk data. To avoid this, use dynamic memory allocation instead.
EDIT: Also, you should use memset instead of a for loop to zero an array. It's much faster.
The "arr" which you allocate in "makeArray()" is local. and when the functione is over the array is release. When you back to main you get garbage.
What you want to do, is to use the "new" operator to allocate this new array to be used in all program, unless you will free this memory by "delete".
so you can set your makeArray() to:
int* makeArray(int size )
{
int *arr = new[size];
for(int i=0;i<size;i++)
{
arr[i]=0;
}
return arr;
}
the in you main you need to initialize your arry by:
int * arrPtr = makeArray(10);
just don't forget to release this memory after you finsh:
delete[] arrPtr ;

How to access a local variable from a different function using pointers?

May I have any access to a local variable in a different function? If so, how?
void replaceNumberAndPrint(int array[3]) {
printf("%i\n", array[1]);
printf("%i\n", array[1]);
}
int * getArray() {
int myArray[3] = {4, 65, 23};
return myArray;
}
int main() {
replaceNumberAndPrint(getArray());
}
The output of the piece of code above:
65
4202656
What am I doing wrong? What does the "4202656" mean?
Do I have to copy the whole array in the replaceNumberAndPrint() function to be able to access it more than the first time?
myArray is a local variable and as thus the pointer is only valid until the end of its scope (which is in this case the containing function getArray) is left. If you access it later you get undefined behavior.
In practice what happens is that the call to printf overwrites the part of the stack used by myArray and it then contains some other data.
To fix your code you need to either declare the array in a scope that lives long enough (the main function in your example) or allocate it on the heap. If you allocate it on the heap you need to free it either manually, or in C++ using RAII.
One alternative I missed (probably even the best one here, provided the array is not too big) is to wrap your array into a struct and thus make it a value type. Then returning it creates a copy which survives the function return. See tp1's answer for details on this.
You can't access a local variable once it goes out of scope. This is what it means to be a local variable.
When you are accessing the array in the replaceNumberAndPrint function the result is undefined. The fact it appears to work first time is just a fortunate coincidence. Probably the memory location you are pointing to is unallocated on the stack and is still correctly set for the first call, but the call to printf then overwrites this by pushing values onto the stack during its operation which is why the second call to printf displays something different.
You need to store the array data on the heap and pass a pointer, or in a variable that remains in scope (e.g. a global or something scoped within the main function).
Try something like that. The way you do it "kills" myArray cause if it locally defined.
#include <stdio.h>
#include <stdlib.h>
void replaceNumberAndPrint(int * array) {
printf("%i\n", array[0]);
printf("%i\n", array[1]);
printf("%i\n" , array[2]);
free(array);
}
int * getArray() {
int * myArray = malloc(sizeof(int) * 3);
myArray[0] = 4;
myArray[1] = 64;
myArray[2] = 23;
//{4, 65, 23};
return myArray;
}
int main() {
replaceNumberAndPrint(getArray());
}
More : http://www.cplusplus.com/reference/clibrary/cstdlib/malloc/
Edit: As Comments correctly pointed out: A better way to do it would be that :
#include <stdio.h>
#include <stdlib.h>
void replaceNumberAndPrint(int * array) {
if(!array)
return;
printf("%i\n", array[0]);
printf("%i\n", array[1]);
printf("%i\n" , array[2]);
}
int * createArray() {
int * myArray = malloc(sizeof(int) * 3);
if(!myArray)
return 0;
myArray[0] = 4;
myArray[1] = 64;
myArray[2] = 23;
return myArray;
}
int main() {
int * array = createArray();
if(array)
{
replaceNumberAndPrint(array);
free(array);
}
return 0;
}
myArray goes out of scope as soon as you leave getArray. You need to allocate space for it on the heap instead.
Your code invokes Undefined Behaviour because myArray goes out of scope as soon as getArray() returns and any attempt to use (dereference) the dangling pointer is UB.
Local variables go out of scope upon return, so you can't return a pointer to a local variable.
You need to allocate it dynamically (on the heap), using malloc or new. Example:
int *create_array(void) {
int *array = malloc(3 * sizeof(int));
assert(array != NULL);
array[0] = 4;
array[1] = 65;
array[2] = 23;
return array;
}
void destroy_array(int *array) {
free(array);
}
int main(int argc, char **argv) {
int *array = create_array();
for (size_t i = 0; i < 3; ++i)
printf("%d\n", array[i]);
destroy_array(array);
return 0;
}
Alternatively, you can declare the array as static, keeping in mind the semantics are different. Example:
int *get_array(void) {
static int array[] = { 4, 65, 23 };
return array;
}
int main(int argc, char **argv) {
int *array = get_array();
for (size_t i = 0; i < 3; ++i)
printf("%d\n", array[i]);
return 0;
}
If you don't know what static means, read this question & answer.
Right way to do this is as follows:
struct Arr {
int array[3];
};
Arr get_array() {
Arr a;
a.array[0] = 4;
a.array[1] = 65;
a.array[2] = 23;
return a;
}
int main(int argc, char **argv) {
Arr a = get_array();
for(size_t i=0; i<3; i++)
printf("%d\n", a.array[i]);
return 0;
}
To understand why you need to do this, you need to know how sizeof(array) works. C (and thus c++) tries hard to avoid copying the array, and you need the struct to go past that. Why copying is needed is because of scopes -- the get_array() function's scope disappears and every value still needed from that scope will need to be copied to calling scope.
C++ solution:
"May I have any access to a local variable in a different function? If so, how?"
The answer is no, not after the function has ended. Local variables are destroyed at that point.
In C++ the way to deal with returning arrays is to manage them in a container like a std::array (fixed size) or a std::vector (dynamic size).
Eg:
void replaceNumberAndPrint(const std::array<int, 3>& array) {
printf("%i\n", array[0]);
printf("%i\n", array[1]);
printf("%i\n", array[2]);
}
std::array<int, 3> getArray() {
std::array<int, 3> myArray = {4, 65, 23};
return myArray;
}
In the second function the returned value is optimized by the compiler so you don't pay the price of actually copying the array.
In this code you have used pointer to local objects but when a function returns all local variables goes out of scope. If you will allocate memory (using malloc() function for allocation) then no data will be lost or overwrite.
int* getArray(int size) {
int *myArray = (int*)malloc(size*sizeof(int));
myArray[0] = 4;
myArray[1] = 65;
myArray[2] = 23;
return myArray;
}
int main() {
int i;
int *vector = getArray(3);
for(i=0;i<3;i++)
{
printf("%i\n",vector[i]);
}
getch();
return 0;
}
This code will print all the array elements and no overwritten will be happened.
Static ..or.. Global within your .c will do the trick ;)
However the entire time the program will occupy those 3 bytes BUT you avoid doing malloc on simple things like this (malloc recommended for big arrays)
On the other hand if the outside function modify the pointer, then the internal 'myArray' will be modified cause it points to it, that's it
int myArray[3];
int * getArray() {
myArray[0] = 4;
myArray[1] = 65;
myArray[2] = 23;
return myArray;
}