I have this very simple c++ program. It’s been years that I did some C++ so I thought I might give it a spin one more time. But I am amazed by the output I am getting. It was supposed to be a simple program and it’s causing me some headaches already.
//2.cpp
//This program asks for the radius of the circle and
//prints the area of that circle
#include <iostream>
#include <stdlib.h>
int* area(char* radius[], int size)
{
int* pointer;
int areas[size];
pointer = areas;
for(int i = 0; i < size; i++)
{
areas[i] = 3.1416*atoi(radius[i])*atoi(radius[i]);
}
return pointer;
}
void print(char* radius[], int* area1, int size)
{
std::cout<<area1[2]<<std::endl; //This prints fine
for(int i = 0; i < size; i++)
{
std::cout << area1[i]; //This doesn't
std::cout << "Area for " << radius[i] << " is: " << area1[i] << std::endl;
}
}
int main(int argc, char* argv[])
{
if(argc > 1)
{
print(&argv[1],area(&argv[1],argc-1),argc-1);
}
else
{
//Please ignore this
}
return 0;
}
Input
./a.out 1 4 2 7 8
Output:-
12
134520896
Area for 1 is: 134520896
10
Area for 4 is: 10
-1217419175
Area for 2 is: -1217419175
-1217056780
Area for 7 is: -1217056780
-1217056780
Area for 8 is: -1217056780
Your
areasarray has automatic storage duration and goes out of scope onceareareturns; then dereferencingpointeris undefined behavior. Please use C++ idioms likestd::stringandstd::vectorinstead of C pointers.Here is an improved (but still not optimal) version of your code:
Unfortunately compilers often cannot detect such errors. Use a tool like Valgrind to find them. For example, running your original code through Valgrind produces many errors for me:
while my version produces no errors.