Array Pointer Returns Garbage [duplicate] - c++

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
C++ correct way to return pointer to array from function
(7 answers)
Closed 5 years ago.
I am trying to subtract two integers of the same size without using an explicit loop using valarray.
For this purpose I've written a function i.e subtract(int *firstarray, int *secondarray). However, the subtraction occurs correctly in function as printed out. But when returned to main() the first two values of array contain garbage. What is my mistake?
int* subtract(int* lastline, int* firstline){// takes two user defined arrays and performs subtraction
std::valarray<int> foo (firstline, 7); // 6 6 5 4 5 6 7
std::valarray<int> bar (lastline,7); // 1 8 8 8 8 8 8
std::valarray<int> res (7);
res=bar-foo; //subtracts two valarrays
for (size_t i=0; i<NUMBEROFCLASSES;i++){
cout<<res[i]<<" "; //prints 5 -2 -3 -4 -3 -2 -1
}
return &res[0];
}
int main(){
int first[7]={6,6,5,4,5,6,7};
int second[7]={1,8,8,8,8,8,8};
int *e= subtract(first, second);
cout<<endl;
for(int i=0; i<7;i++){
cout<<e[i]<<" "; // prints 0 0 -3 -4 -3 -2 -1
}
return 1;
}

res is a variable with automatic storage duration, meaning that it will be destroyed right when the function exits. e is a dangling pointer, so accessing it is undefined behavior. You can return a std::valarray instead.
std::valarray<int> subtract(int* lastline, int* firstline){
// Stuff
return res;
}

Related

why does the array of lower initialized index value throw garbage value [duplicate]

This question already has answers here:
Uninitialized variable behaviour in C++
(4 answers)
(Why) is using an uninitialized variable undefined behavior?
(7 answers)
What happens when I print an uninitialized variable in C++? [duplicate]
(4 answers)
Closed 6 months ago.
In the below program I get garbage values for indexes like 2,4 etc
main()
{
int j, arr[10] , a;
int n = 10;
while (n--)
{
scanf("%d", &a);
printf("%d \n", ++arr[a]);
}
}
output
9
0
4
1781349929
3
0
2
395049983
1
0
but when I increase the array initialized index to a large number every index value is assigned zero
main()
{
int j, arr[10000] , a;
int n = 10;
while (n--)
{
scanf("%d", &a);
printf("%d \n", ++arr[a]);
}
}
output
9
0
4
0
3
0
2
0
1
0

C++ Pointers assignment gives unexpected(?) results

int* snap = nullptr;
int last = -1;
void func(int* md){
if(snap!=nullptr) {
last = *snap;
}
snap = md;
cout<<last<< " "<<*snap<<endl;
}
int main() {
for(int i =0;i<10;i++) {
int arg = i;
func(&arg);
}
return 0;
}`
Output
-1 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
Shouldn't the 'last' variable have the previous iteration's value of 'snap'. But the values are equal. What am I doing wrong here?
On the second iteration of your for loop, snap points to a dangling pointer. The int arg that it points to has fallen out of scope.
While it is a dangling pointer, you dereference it, causing undefined behavior.

Why do `&n` and `&n + 1` differ by `4` instead of `1`? [duplicate]

This question already has answers here:
Why a pointer + 1 add 4 actually
(6 answers)
Closed 1 year ago.
I would expect the values of &n and &n + 1 to be adjacent memory boxes, so their address should differ by 1. However, every time I run these commands, I get addresses that differ by 4 (for example 0056F800 and 0056F804). Why does this happen?
#include <iostream>
using namespace std;
int main()
{
int n = 3;
cout << &n << endl;
cout << &n + 1;
}
Pointer arithmetic creates a pointer to a specific element of an array (or equivalently, a single object which is treated as an array of size 1), so it effectively changes the value of the pointer by multiples of the element size.
On your system an int is apparently 4 bytes in size so by adding 1 to an int * it creates a pointer value 4 larger than the original value.

Why is this code outputting so many numbers? [duplicate]

This question already has answers here:
ARRAYSIZE C++ macro: how does it work?
(7 answers)
c++ sizeof(array) return twice the array's declared length
(6 answers)
Closed 3 years ago.
Starting with two arrays a and b, I am trying to output a matrix c with dimensions sizeof(a) and sizeof(b), whose entries are the product of every pair of the Cartesian product of a and b.
Theses products are also stored in a two dimensional array c.
My code is below.
#include <iostream>
#include <string>
int main()
{
int a[]= { 1,2,3,4,5,5 };
int b[]= { 1,23,2,32,42,4 };
int c[sizeof(a)][sizeof(b)];
for (int i = 0; i < sizeof(a); i++) {
for (int j = 0; j < sizeof(b); j++) {
c[i][j] = a[i]* b[j] ;
std::cout << c[i][j] << " ";
}
std::cout << "\n";
}
return 0;
}
My output is:
1 23 2 32 42 4 -858993460 -858993460 1 2 3 4 5 5 -858993460 16710224 15543422 1 2161328 2122464 16710312 15543008 196436084 15536213
2 46 4 64 84 8 -1717986920 -1717986920 2 4 6 8 10 10 -1717986920 33420448 31086844 2 4322656 4244928 33420624 31086016 392872168 31072426
3 69 6 96 126 12 1717986916 1717986916 3 6 9 12 15 15 1717986916 50130672 46630266 3 6483984 6367392 50130936 46629024 589308252 46608639
...
This is just a small part of the output.
sizeof(a) is not the length of the array, it is the number of bytes required to store it.
Since the element type of the array is larger than one byte each, the numbers are different.

Print contents of array modified in function

In my main() function I have declared an array of type int with the numbers 1 to 10. I then have two other functions of type int* that take this array and its size as parameters, perform some operations, and each returns a pointer to the new array. Where I'm having issues is with a third function that prints the contents of the array.
#include <iostream>
using namespace std;
const int SIZE_OF_ARRAY = 10;
int main() {
int array[SIZE_OF_ARRAY] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *ptr1 = 0;
ptr1 = function1(array, SIZE_OF_ARRAY);
print(array, SIZE_OF_ARRAY);
cout << endl;
int *ptr2 = 0;
ptr2 = function2(array, SIZE_OF_ARRAY);
print(array, SIZE_OF_ARRAY);
return 0;
}
void print(int array[], const int SIZE_OF_ARRAY)
{
for (int i = 0; i < (SIZE_OF_ARRAY * 2); i++)
{
cout << array[i] << " ";
}
}
int* function1(int array[], const int SIZE_OF_ARRAY)
{
int *ptr = new int[SIZE_OF_ARRAY];
// Do stuff.
return ptr;
}
int* function2(int array[], const int SIZE_OF_ARRAY)
{
int *ptr2 = new int[SIZE_OF_ARRAY * 2];
// Create new array double in size, and set contents of ptr2
// to the contents of array. Then initialize the rest to 0.
return ptr2;
}
As expected here, the result of calling the print() function twice is something like:
1 2 3 4 5 6 7 8 9 10 465738691 -989855001 1483324368 32767 -1944382035 32767 0 0 1 0
1 2 3 4 5 6 7 8 9 10 465738691 -989855001 1483324368 32767 -1944382035 32767 0 0 1 0
But I want the result to be like this instead:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 0 0 0 0 0 0 0 0 0 0
How can I accomplish this? (Note that for this assignment I'm using C++98). Thanks in advance.
new int[SIZE_OF_ARRAY] allocates memory, but doesn't assign values to the array elements. What you are seeing is what was in that memory when it got allocated for the array. You can change your function2 to assign zeroes to array elements, if that's what you want.
First of all, you want to print different number of elements on the two calls to print, so you should not delegate deciding whether to multiply the size by two to the print, but rather do it on the calling side. Change the print function to only iterate up to SIZE_OF_ARRAY, and change the two places where you call it to:
print(ptr1, SIZE_OF_ARRAY);
and
print(ptr2, SIZE_OF_ARRAY * 2);
correspondingly.
Now, I assume that your second function does assign values to all 20 elements, but if it does not, the ones to which it did not assign values would continue containing garbage. To get around it, just initialize them at the beginning of the second function:
int *ptr2 = new int[SIZE_OF_ARRAY * 2];
for (size_t i = 0; i < SIZE_OF_ARRAY * 2; ++ i) ptr2[i] = 0;
With these two changes you should get the desired behavior.
Also, if you allocate something with new[], you need to delete it with delete[], otherwise you get a memory leak. Add these two lines at the end of main:
delete[] ptr1;
delete[] ptr2;
Note, that using delete instead of delete[] would be wrong in this case. If something is allocated as an array, it must be deleted as an array.