This is a follow-up question to a previous question (now that the actual issue is different):
int main()
{
mpz_t p, q, n, phi_n, e, d;
mpz_inits(p, q, n, phi_n, e, d, NULL);
generate_pq(p,q);
compute_n(n,p,q);
compute_phiN(phi_n,p,q);
mpz_clear(p,q,NULL);
select_e(e,phi_n);
compute_d(d,e,phi_n);
mpz_clear(phi_n);
mpz_t* m;
int size=0;
store_m(m,size);
mpz_t* c;
encrypt(c,m,size,e,n);
return 0;
}
Here are the relevant functions:
void store_m(mpz_t m[], int& size)
{ /* m = original message */
printf("\nMessage: ");
char* buffer = new char[128];
cin.getline(buffer,128);
size = strlen(buffer); //size = buffer
m = new mpz_t[size];
for(int i=0; i<size; i++) {
mpz_init(m[i]);
mpz_set_ui(m[i],(int)buffer[i]);
}
delete buffer;
}
void encrypt(mpz_t*& c, mpz_t m[], const int size,
const mpz_t e, const mpz_t n)
{ /* c = cipher */
cout << "1" << endl;
c = new mpz_t[size];
cout << "2" << endl;
for(int i=0; i<size; i++) {
cout << "3" << endl;
mpz_init(c[i]);
cout << "4" << endl;
mpz_powm(c[i],m[i],e,n);
cout << "5" << endl;
mpz_clear(m[i]);
cout << "6" << endl;
} /* c = m^e(mod n) */
cout << "7" << endl;
}
When I execute, the program goes into encrypt() but seg faults at the 4th cout.
Remember C++ is pass-by-value unless you explictly say you're passing by reference using the & operator. In store_m() you are allocating and assigning to m inside the function. That won't work since you're passing m by value. As a result the main() function never sees the assignment to m since store_m() has only a local copy of m. You are therefore passing an uninitialized variable to encrypt(). Either allocate m in main() or declare store_m() like so:
void store_m( mpt_t*& m, int& size);
BTW: You're not segfaulting at the 4th cout. You're segfaulting right after when the encrypt() function prepares to call mpz_powm(). The actual crash is the dereference m[i] (since m is unitialized).
Related
I need to print an array by implementing the use of a function before the main function. So I tried the following function:
int* printArr(int* arr)
{
for (int i = 0; i < 5; i++) {
cout << arr[i];
}
return arr;
}
I encountered two problems when implementing this into the whole code.
First, this is printing what I think is the address of the array and not the actual array. Pretty sure this is because of the return arr; in line 10. But if I do not write return then the code will produce an error. How can I fix this?
Second, I do not understand the second argument printArr has. In line 19, you can see cout << printArr(arr, 5) << endl;. How come there is a single numeric value, that one being 5 in this case, as an argument? How can I account for this in my function?
Please keep in mind that I am new to C++ and coding in general. Also, this code was given to me, hence why I do not understand certain aspects of it.
This is my code so you can see what I mean:
#include <iostream>
using namespace std;
// Declare function printArr here
int* printArr(int* arr)
{
for (int i = 0; i < 5; i++)
{cout << arr[i];}
return arr;
}
int main()
{
int arr[5] = {1, 3, 5, 7,9};
int last_num = arr[sizeof(arr)/sizeof(int)-1];
cout << "Before reversing" << endl;
cout << printArr(arr, 5) << endl;
// reverse "arr" using reference(&)
cout << "After reversing" << endl;
printArr(arr, 5);
return 0;
}
The declaration and implementation of printArr() is all wrong.
First, this is printing what I think is the address of the array and not the actual array.
The printArr() function itself is printing the contents of the array (well, the first 5 elements anyway), and then returning the address of the array. It is main() that is printing that address afterwards, when it passes the return value of printArr() to std::cout <<.
Pretty sure this is because of the return arr; in line 10. But if I do not write return then the code will produce an error. How can I fix this?
By getting rid of the return type altogether. There is no good reason to return the array pointer at all in this example, let alone to pass that pointer to std::cout. So printArr() should be returning void, ie nothing.
Second, I do not understand the second argument printArr has. In line 19, you can see cout << printArr(arr, 5) << endl;. How come there is a single numeric value, that one being 5 in this case, as an argument?
Because main() is passing in the element count of the array (5) so that printArr() can know how many elements to actually print, instead of hard-coding that value in the loop. However, your declaration of printArr() does not have a 2nd parameter with which to accept that value, that is why you are getting errors.
How can I account for this in my function?
By adding a 2nd parameter in the function declaration, eg:
#include <iostream>
using namespace std;
// Declare function printArr here
void printArr(int* arr, int size)
{
for (int i = 0; i < size; i++)
{
cout << arr[i] << ' ';
}
cout << endl;
}
int main()
{
int arr[5] = {1, 3, 5, 7, 9};
const int count = sizeof(arr)/sizeof(arr[0]);
int last_num = arr[count-1];
cout << "Before reversing" << endl;
printArr(arr, count);
// reverse "arr" using reference(&)
cout << "After reversing" << endl;
printArr(arr, count);
return 0;
}
Live Demo
#include <stdio.h>
#include <stdlib.h>
double matrixMultiply(double a[100][100],double b[100][100], int rowA,int colB,int colArowB){
double c[100][100];
int i,j,k;
for(i=0;i<rowA;i++)
for(j=0;j<colB;j++){
for(k=0;k<colArowB;k++)
c[i][j]=c[i][j]+a[i][k]+b[k][j];}
return c;
}
int main()
{
double a[100][100],b[100][100];
int n,m,o,p,i,j;
printf("%s \n", "Nr. linii A:");
scanf("%d",&n);
printf("%s \n", "Nr. coloane A:");
scanf("%d",&m);
printf("%s \n", "Nr. linii B:");
scanf("%d",&o);
printf("%s \n", "Nr. coloane B:");
scanf("%d",&p);
printf("%s \n", "A=");
for(i=0;i<n;i++)
for(j=0;j<m;j++)
scanf("%d", &a[i][j]);
printf("%s \n", "B=");
for(i=0;i<o;i++)
for(j=0;j<p;j++)
scanf("%d", &b[i][j]);
if(m==o){
printf("Matricile se pot inmulti");
cout<<matrixMultiply(a,b,n,m,p);
return 0;}
else printf("Matricile nu se pot inmulti");
return 0;
}
I should multiply 2 matrices A & B, but I don't know how to return the matrix C, can somebody help?
There is an error returning the matrix C,also do I need a for to print the matrix C?
I should multiply 2 matrices A & B, but I don't know how to return the matrix C, can somebody help?
return c;
will not work since the array decays to a pointer. Not only that, the pointer becomes invalid as soon as the function returns since c is a function local variable.
If the size of the matrix is known at compile time, you may use std::array. If the size of the matrix is known at run time only, you should use std::vector of std::vector.
std::array<std::array<int, 100>, 100> matrixMultiply(...) {}
or
std::vector<std::vector<int>> matrixMultiply(...) {}
As others have stated you could use the std::vector<std::vector<int>> but if you still want to use a 2D, array you need to dynamically allocate the 2D array in the function using a malloc and return a double* matrixMultiply(double a[100][100],double b[100][100], int rowA,int colB,int colArowB) or you could also allocate in the main function and just pass the address reference cout<<matrixMultiply(&a,&b,n,m,p);
vector maybe a better choice for this case in C++.
the function maybe looks like the following, and the entire program for this question is here
using namespace std;
typedef vector<double> MatrixRow;
typedef vector<MatrixRow> Matrix;
Matrix matrix_multiply(const Matrix &left, const Matrix &right)
{
// Validate conditions of multiplication of matrices
if (left.empty())
{
cerr << "Left matrix is empty." << endl;
exit(-1);
}
if (right.empty())
{
cerr << "Right matrix is empty." << endl;
exit(-1);
}
const int leftRowCount = left.size();
const int leftColumnCount = left.front().size();
const int rightRowCount = right.size();
const int rightColumnCount = right.front().size();
if (leftColumnCount != rightRowCount)
{
cerr << "The number of columns of the left matrix is not the same as the number of columns of the right matrix." << endl;
exit(-1);
}
cout << "Calculate steps" << endl
<< "=====" << endl;
// Calculation
Matrix matrix(leftRowCount);
for (int i = 0; i < leftRowCount; i++)
{
matrix.at(i).resize(rightColumnCount);
for (int j = 0; j < rightColumnCount; j++)
{
matrix.at(i).at(j) = 0;
cout << "M(" << i << "," << j << ") = ";
for (int k = 0; k < leftColumnCount; k++)
{
cout << "L(" << i << "," << k << ") + R(" << k << "," << j << ")";
if (k < leftColumnCount - 1)
{
cout << " + ";
}
matrix.at(i).at(j) += left.at(i).at(k) * right.at(k).at(j);
}
cout << endl;
}
}
cout << endl;
return matrix;
}
More about identifier naming:
In declarations
An identifier can be used to name objects, references,
functions, enumerators, types, class members, namespaces, templates,
template specializations, parameter packs, goto labels, and other
entities, with the following exceptions:
the identifiers that are keywords cannot be used for other purposes;
the identifiers with a double underscore anywhere are reserved; the
identifiers that begin with an underscore followed by an uppercase
letter are reserved;
the identifiers that begin with an underscore are
reserved in the global namespace.
more about identifier naming in C++, visit here for details.
I've encountered a problem while trying to create a code which converts decimal numbers to binary, using functions. At first I created the code using only main function and it worked fine, but decided to modify it to use function. I believe code is written right, however when I try to cout my answer I get a big number like 115120160758866453687091316369641637416.
This is the code
#include <iostream>
#include <math.h>
using namespace std;
int* unsigned_dec(int dec_M) { //function for converting absolute part of numbers
int bin[8] = { 0,0,0,0,0,0,0,0 };
int ind = 7;
int arr_ind = 0;
for (int base = (int)abs(dec_M); base > 0; base = base / 2) {
if (base % 2 == 0) {
bin[arr_ind] = 0;
ind--;
}
else {
bin[arr_ind] = 1;
ind--;
}
arr_ind++;
}
return bin;
}
int main() {// main function
int dec_N;
cin >> dec_N;
int* bin_main = unsigned_dec(dec_N); //we are not sure if we are assigning the returned value of function to array in correct
for (int i = 0; i <= 7; i++) {
cout << bin_main[i];
}
cout << endl;
return 0;
}
then I tried to change the cout code to
cout << bin_main[0] << bin_main[1] << bin_main[2] << bin_main[3] << bin_main[4] << bin_main[5] << bin_main[6] << bin_main[7] << endl;
And this worked fine.
Then I wrote the same 2nd variant of cout in other way
cout << bin_main[0];
cout << bin_main[1];
cout << bin_main[2];
cout << bin_main[3];
cout << bin_main[4];
cout << bin_main[5];
cout << bin_main[6];
cout << bin_main[7];
cout << endl;
and my code started to cout the same strange number. I think that all 3 ways of couts are almost the same (especially 2 and 3), but don't understand what makes it not to work.
int bin[8] = { 0,0,0,0,0,0,0,0 };
is allocated on stack. You should either allocate bin on heap
auto bin = std::unique_ptr<int, std::default_deleter<int[]>>(new int[8]);
or even better, use std::vector
you are returning pointer to local array of intbin[] in unsigned_dec. This array on stack of function unsigned_dec will get invalidated once another function from main gets called i.e cout operator .
As others have already mentioned: A function should never return a pointer to a local variable. Local variable is not valid when the function returns.
A better way is to use a vector and just make the function return the vector.
Something like:
#include <iostream>
#include <math.h>
using namespace std;
//function for converting absolute part of numbers
vector<int> unsigned_dec(int dec_M) {
vector<int> bin; // Create a vector
bin.resize(8, 0); // Fill it with 8 elements initialized to zero
int arr_ind = 0;
// Note: added check for arr_ind being valid
for (int base = (int)abs(dec_M); base > 0 && arr_ind < 8; base = base / 2) {
if (base % 2 == 0) {
bin[arr_ind] = 0;
}
else {
bin[arr_ind] = 1;
}
arr_ind++;
}
return bin; // Return the vector
}
int main() {
int dec_N;
cin >> dec_N;
vector<int> bin_main = unsigned_dec(dec_N);
for (int i = 0; i < bin_main.size(); i++) {
cout << bin_main[i];
}
cout << endl;
return 0;
}
The issue I'm having is I'm trying to return an array from the function EnterNumber() and display it in the main, but its coming out fairly crazy. I went through with the debugger and the numbers are correct in the debugger, just not correct in once it prints to the screen.
I realize there's a global const int in my program, but it was sanctioned by my professor who wanted us to do it just this time for this program.
Just looking for a nudge on why its printing incorrectly. Thank you.
#include <iostream>
using namespace std;
void EnterNumber(int Number[]);
const int SIZE=20;
int main()
{
int LargeNumber1[SIZE];
int LargeNumber2[SIZE];
for (int Counter1=0; Counter1<=19; ++Counter1)//zeros arrays out
{
LargeNumber1[Counter1]=0;
LargeNumber2[Counter1]=0;
}
EnterNumber(LargeNumber1);
for (int Counter2=0; Counter2<=19; ++Counter2)//display array 1 contents
{
cout << LargeNumber1[SIZE];
}
cout << "\n\n";
EnterNumber(LargeNumber2);
for (int Counter2=0; Counter2<=19; ++Counter2)//display array 2 contents
{
cout << LargeNumber2[SIZE];
}
}
void EnterNumber(int Number[])
{
int TemporaryArray[SIZE];
int PlaceCounter;
char Storage;
PlaceCounter=0;
for (int Counter1=0; Counter1<=19; ++Counter1)//zeros arrays out
{
TemporaryArray[Counter1]=0;
Number[Counter1]=0;
}
cout << "Please enter a large number --> ";
cin.get(Storage);
while (Storage!='\n' && PlaceCounter<SIZE)//puts number in temp array - left aligned
{
TemporaryArray[PlaceCounter]=(Storage-'0');
++PlaceCounter;
cin.get(Storage);
}
--PlaceCounter;//decrement one to get it to work properly with element style counting, else, extra zero at end
for (int A=SIZE-1; PlaceCounter>=0; A--, PlaceCounter--)//transfers old array into new array, right aligned
{
Number[A]=TemporaryArray[PlaceCounter];
}
cout << "\n";
}
This:
for (int Counter2=0; Counter2<=19; ++Counter2)
{
cout << LargeNumber1[SIZE];
}
should be this:
for (int Counter2=0; Counter2<SIZE; ++Counter2)
{
cout << LargeNumber1[Counter2];
}
You were repeatedly printing a number that was just beyond the end of the array.
Can someone please tell me what is wrong with the following code ? I am trying to implement
a graph with a class Node which contains the node id and a vector of pointer to its neighbors. Here is a short version of my code :
#include<vector>
#include<iostream>
using namespace std;
class N {
public:
int i;
vector<N*> v;
N(int i) {
this->i = i;
};
};
int init(N* n1) {
N n2(2);
cout << "pointer " << &n2 << endl;
n1->v.push_back(&n2);
};
int main() {
N n1(1);
init(&n1);
cout << n1.i << endl;
cout << "pointer " << n1.v[0] << endl;
cout << n1.v.at(0)->i << endl;
return 0;
};
The problem is that after the call to the init function, it seems that the node n2 does not exist anymore.
Thanks for your help.
Because n2 is local variable, which will be released after the init function call. Therefore after the init function call, the content reside in its previous address is undefined.
To fix this issue, consider using the new operator:
int init(N* n1) {
N* n2 = new N(2);
cout << "pointer " << n2 << endl;
n1->v.push_back(n2);
};
Or simply
int init(N* n1) {
n1->v.push_back(new N(2));
};
Since the instance you added are created by the new operator, you need to release their memory by using the delete operator (for example, in N's destructor):
~N() {
for (int i = 0; i < v.size(); ++i) {
delete v[i];
}
v.clear();
}
You need to learn about scope. n2 goes out of scope (and therefore its memory address) at the end of the function init
int init(N* n1) {
N n2(2);
cout << "pointer " << &n2 << endl;
n1->v.push_back(&n2);
} // life time of n2 ends here
n2 resides on stack. Its life time ends as soon as init returns. So having a reference to it results in undefined behavior. Try -
n1->v.push_back(new N(2));