compiling in linux using g++ - c++

I have following code which is simply tokenizing an array and then deviding on the basis of '<' and '>' characters. It is running fine in VS community 2019 but when I run it in Linux using g++ command it gives
Free(): invalid pointer
and
Aborted (core dumped)
errors. What am I doing wrong.
PS: error seems to be in the instructions where I am deallocating b in rangbrk and langbrk because when I put it in comments it runs fine in Linux too. But it runs fine in VS 2019 anyways.
//#include <sys/types.h>
//#include <sys/wait.h>
//#include <sys/stat.h>
#include <fcntl.h>
//#include <unistd.h>
#include<string.h>
#include<stdio.h>
#include<fstream>
#include<iostream>
#include<stdlib.h>
using namespace std;
//_________________________________________________________
int reads(char str[])
{//a simple function to get input
int s = 1;
char buffer[100];
cout << "enter command" << endl;
cin.getline(buffer, 100);
if (strlen(buffer) == 0)
{
cout << "Couldnt get input\n";
return 0;
}
for (int i = 0; i <= strlen(buffer); i++)
{
str[i] = buffer[i];
if (buffer[i] == 32)
s++;
}
return s;
}
//____________________________________________________________
int tokenizing(char** a, char str[], char buff[50], int x)
{//a function to devide a complete string into smaller parts
//also stores '/bin/command' into buff to pass as first parameter of execvp
int k = 0, m = 0;
bool check = false;
for (int i = 0; i < x; i++)
{
a[i] = new char[50];
for (int j = 0; str[k] != 32; j++)
{
if (str[k] == 0)
{
check = true;
break;
}
a[i][j] = str[k];
if (i == 0)
buff[j + 5] = str[k];
k++;
a[i][j + 1] = 0;
if (i == 0)
buff[j + 6] = 0;
}
m++;
k++;
if (check)
break;
}
return m;
}
//__________________________________________________________
void rangbrk(char**& a, char**& b, int& x, char filename[])
{//saperates the array before and after '>'
for (int i = 0; i < (x - 2); i++)
{
b[i] = new char[50];
for (int j = 0; j < 50; j++)
{
b[i][j] = a[i][j];
}
}
b[x - 2] = NULL;
for (int i = 0; i < 50; i++)
{
filename[i] = a[x - 1][i];
}
char** c;//temprory pointer to swap a and b
c = a;
a = b;
b = c;
x = x - 2;
for(int i=0;i<x-1;i++)
{
delete [] b[i];
}
b=NULL;
}
//__________________________________________________________
void langbrk(char** &a, char** &b, int& x, int index, char filename[])
{//saperates the array before and after '<'
int k = 0;
for (int i = 0; i < x; i++)
{
if ((i != index) && (i != index - 1))
{
b[k] = new char[50];
for (int j = 0; j < 50; j++)
{
b[k][j] = a[i][j];
}
k++;
}
}
b[x - 2] = NULL;
for (int i = 0; i < 50; i++)
{
filename[i] = a[index - 1][i];
}
char** c;//temprory pointer to swap a and b
c = a;
a = b;
b = c;
x = x - 2;
for(int i=0;i<x-1;i++)
{
if(b[i]!=NULL)
delete [] b[i];
}
b=NULL;
}
//__________________________________________________________
int main()
{
char buff[50] = { "/bin/" };
char str[100];
char exit[5] = { 'e','x','i','t',0 };
char outfile[50];
char infile[50];
int x = reads(str);
char** a;
a = new char* [x];
int s = tokenizing(a, str, buff, x);
a[s] = NULL;
bool flag = false;
for (int i = 0; a[i] != NULL; i++)
cout << a[i] << endl;
cout << s << endl;;
for (int i = 0; i < s; i++)
{
if (a[i][0] == '>')//checks if it need to print in a file
{
cout << i;
char** b;
b = new char* [s - 2];
rangbrk(a, b, s, outfile);
flag = true;
cout << "New" << endl;
for (int j = 0; j < s; j++)
cout << a[j] << endl;
i = 0;
}
else if (a[i][0] == '<')
{
cout << i;
char** c;
c = new char * [s - 2];
langbrk(a, c, s, i, infile);
cout << "New" << endl;
for (int j = 0; j < s; j++)
cout << a[j] << endl;
i = 0;
}
}
}
The reads function gets input, tokenizing tokenized the string in form of words. langbrk copies the string having index 1 less than index of '<' in infile and removes them both from main char** a. rangbrk removes '>' and string succeeding it from a and stores it in outfile

Related

matrix multiplication using shared memory and fork

i have assigment to create c++ program which will multiple 2 uknown size matrix using fork and shared memory, I have write this code but at the end for multiplication result i get all zeros. Sorry for mess code im new in this.
`
`#include<iostream>
#include<math.h>
#include<vector>
#include<signal.h>
#include<unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include<sys/wait.h>
using namespace std;
int l, m, n, job_numb;
key_t id_shared_mem;
int **B, **C, **A;
int **generateMatrix(int **matrix, int iterator, int vel){
for (int i = 0; i < iterator; i++)
{
matrix[i] = new int[vel];
for (int j = 0; j < vel; j++)
{
matrix[i][j] = (rand() % 9);
}
}
return matrix;
}
int **generateMatrixC(int **matrix, int iterator, int vel)
{
for (int i = 0; i < iterator; i++)
{
matrix[i] = new int[vel];
}
return matrix;
}
void *writeMatrixResult(int **matrix, int stupac, int red)
{
for (int i = 0; i < stupac; i++)
{
for (int j = 0; j < red; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
return NULL;
}
void write()
{
cout << "Mnozenik = " << endl;
writeMatrixResult(A, l, m);
cout << "Mnozitelj = " << endl;
writeMatrixResult(B, m, l);
cout << "Umnozak = " << endl;
writeMatrixResult(C, l, l);
}
void abort(int sig) {
if (sig == SIGINT) {
for (int i = 0; i < job_numb; i++) wait(NULL);
shmdt(A);
shmdt(B);
shmctl(id_shared_mem, IPC_RMID, NULL);
} else {
write();
shmdt(A);
shmdt(B);
shmctl(id_shared_mem, IPC_RMID, NULL);
}
exit(0);
}
void proces(int procesId)
{
while (job_numb > procesId)
{
int i = 0;
while (i < l)
{
int j = 0;
C[procesId][i] = 0;
while (m > j)
{
C[procesId][i] = C[procesId][i] + A[procesId][j] * B[j][i];
j++;
}
i++;
}
procesId++;
}
}
int main(int argc, char ** argv) {
if (argc != 4) {
cout << " unesite 3 argumenta!" << endl;
return 0;
}
l = atoi(argv[1]);
m = atoi(argv[2]);
n = atoi(argv[3]);
job_numb = l / n;
if (l % n) {
job_numb++;
}
id_shared_mem = shmget(IPC_PRIVATE, sizeof(int) * 10, 0600);
sigset(SIGINT, abort);
A = (int **)shmat(id_shared_mem, NULL, 0);
B = A + l;
C = B + l * m*m;
A = new int *[l];
B = new int *[m];
C = new int *[l];
srand(time(NULL));
A = generateMatrix(A,l, m );
B = generateMatrix(B,m,l);
C = generateMatrixC(C,l,l);
for (int i = 0; i < n; i++)
{
switch (fork()) {
case 0: { //dijete
proces(i);
exit(0);
}
case -1: { //greska
cout << "Fatalna pogreska!" << endl;
exit(1);
}
}
}
for (int i = 0; i < job_numb; i++) wait(NULL);
abort(0);
}`
`
i have try to assign only one value to matrix C like c[1][1] = 2 in proces function to see if it will write any, but still im getting all zeros on printl.

Why the simple multiplication would result in some garbled characters?

I try to design a program that implements the multiplication between two big integers(Using C++). But after I complete it, I found that if I input the two integers by the command arguments, the results would be sometimes very weird and sometimes right. Please help me figure out the reason and tell me how to fix it. Thanks (The main function that implements the function of multiplication between two big integers is mul() ).
#include <iostream>
#include <cstring>
#include <stdlib.h>
using namespace std;
void mul(char *c1, char *c2, int len1, int len2);
void printArr(char *c1, char *c2, int len1, int len2);
int main(int argc, char **argv)
{
if (argv[1] != NULL)
{
char cArr1[500], cArr2[500];
for (int i = 0; i < strlen(argv[1]); i++)
{
cArr1[i] = argv[1][i];
}
for (int i = 0; i < strlen(argv[2]); i++)
{
cArr2[i] = argv[2][i];
}
int len1 = strlen(cArr1);
int len2 = strlen(cArr2);
printArr(cArr1, cArr2, len1, len2);
(len1 > len2) ? mul(cArr1, cArr2, len1, len2) : mul(cArr2, cArr1, len2, len1);
exit(100);
}
while (true)
{
cout << "Please input two integers" << endl;
char cArr1[500], cArr2[500];
cin >> cArr1;
if (cArr1[0] == 'q' && cArr1[1] == 'u' && cArr1[2] == 'i' && cArr1[3] == 't')
{
exit(1000);
}
cin >> cArr2;
int parity = 0;
int len1 = strlen(cArr1);
int len2 = strlen(cArr2);
printArr(cArr1, cArr2, len1, len2);
if (cArr1[0] == '-')
{
for (int i = 1; i < len1; i++)
{
cArr1[i - 1] = cArr1[i];
}
parity++;
len1--;
}
if (cArr2[0] == '-')
{
for (int i = 1; i < len2; i++)
{
cArr2[i - 1] = cArr2[i];
}
parity++;
len2--;
}
bool isDigit = true;
for (int i = 0; i < len1; i++)
{
if (!isdigit(cArr1[i]))
{
isDigit = false;
}
}
for (int i = 0; i < len2; i++)
{
if (!isdigit(cArr2[i]))
{
isDigit = false;
}
}
if (!isDigit)
{
cout << "\rInvalid input. Try again" << endl;
continue;
}
if (parity % 2 != 0)
{
cout << "-";
}
(len1 > len2) ? mul(cArr1, cArr2, len1, len2) : mul(cArr2, cArr1, len2, len1);
}
}
void mul(char *bigger, char *smaller, int bigLen, int smallLen)
{
int *bigNum = new int[bigLen];
int *smallNum = new int[smallLen];
for (int i = 0; i < bigLen; i++)
{
bigNum[i] = bigger[bigLen - i - 1] - '0';
}
for (int i = 0; i < smallLen; i++)
{
smallNum[i] = smaller[smallLen - i - 1] - '0';
}
int res[30];
for (int i = 0; i < 30; i++)
{
res[i] = 0;
}
for (int i = 0; i < smallLen; i++)
{
for (int j = 0; j < bigLen; j++)
{
res[i + j] += bigNum[j] * smallNum[i];
}
}
for (int i = 0; i < bigLen + smallLen; i++)
{
int digit = res[i] % 10;
int carry = res[i] / 10;
res[i] = digit;
res[i + 1] += carry;
}
bool null = false;
for (int i = bigLen + smallLen - 1; i >= 0; i--)
{
if (res[i] != 0 && res[i + 1] == 0)
{
null = true;
}
if (null)
{
cout << res[i];
}
}
cout << endl;
}
void printArr(char *c1, char *c2, int len1, int len2)
{
for (int i = 0; i < len1; i++)
{
cout << c1[i];
}
cout << " * ";
for (int i = 0; i < len2; i++)
{
cout << c2[i];
}
cout << " = ";
}
Just initialize your char arrays to empty ones:
char cArr1[500] = {};
char cArr2[500] = {};
then, for the sake of clarity, assign the lengths from your arguments to two integers, casting them since the compiler might warn you about incompatibility between size_t and int.
int lenArg1 = 0;
int lenArg2 = 0;
lenArg1 = (int)strlen ( argv[1] );
lenArg2 = (int)strlen ( argv[2] );
Then, printing the lengths len1 and len2 for debugging purposes only:
int len1 = strlen ( cArr1 );
int len2 = strlen ( cArr2 );
cout << "len1 >> " + to_string(len1) <<endl;
cout << "len2 >> " + to_string(len2) <<endl;
In fact, as #Kevin SUN mentioned, it was possible that your argument reading steps were missing the null characters, however, after running some tests it seems to work fine just by initializing the char arrays.
Also, as mentioned in the comments you need to increase the size reserved for res array, I did it to 500
Compiled with g++ -Wall main.cpp -o calc.exe and running: calc 10 100
Without initialization you get problems like:
after initializing, the output works just fine:

Magic Number output

Alright so I have created this code. However, when i run it, it stops when it displays 104 for the counter??? I am so frustrated because I don't know how this could happen. The purpose of the code is to do the typical magic number output where the rows all add up to the same thing, the columns all add up to the same thing, and the diaganols all add up to the same thing. I believe the functions to do these calculations are correct, but the counter keeps stopping short of the 10000 attempts I am trying to do.
#include <iostream>
#include<time.h>
#include<stdlib.h>
using namespace std;
void getrandom();
void insertnumber(int n);
bool magic();
void create();
const int rows = 3;
const int cols = 3;
int arr[rows][cols] = { {0,0,0}, {0,0,0} , {0,0,0} };
int main() {
int counter = 0;
do
{
counter++;
cout << counter << endl;
getrandom();
if (counter == 100000)
break;
} while (!magic());
create();
cout << "It took " << counter << " tries." << endl;
return 0;
}
void getrandom() {
int n = 0;
const int size = 9;
int oldnum[size];
for (int i = 0; i < rows * cols; i++) {
oldnum[i] = 0;
}
srand(time(NULL)); // had to import the new libraries to use this
bool used = true;
for (int i = 0; i < size; i++) {
do
{
used = true;
n = rand() % 9 + 1;
if (oldnum[n - 1] == 0)
{
oldnum[n - 1] = n;
used = false;
}
} while (used);
insertnumber(n);
}
}
void insertnumber(int n) {
for (int i = 0; i < rows; i++) {
for (int j = 0; i < cols; j++) {
if (arr[i][j] == 0) {
arr[i][j] = n;
return;
}
}
}
}
bool magic() {
int rowsum = arr[0][0] + arr[0][1] + arr[0][2];
for (int i = 1; i < cols; i++)
{
if (arr[i][0] + arr[i][1] + arr[i][2] != rowsum)
return false;
}
for (int j = 0; j < rows; j++)
{
if (arr[0][j] + arr[1][j] + arr[2][j] != rowsum)
return false;
}
if (arr[0][0] + arr[1][1] + arr[2][2] != rowsum)
return false;
if (arr[0][2] + arr[1][1] + arr[2][0] != rowsum)
return false;
return true;
}
void create() {
{
for (int i = 0; i < rows; i++) {
for (int j = 0; i < cols; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
}
You can try using a debugger for such problems.
I think you code crashes because of this:
for (int i = 0; i < rows; i++) {
for (int j = 0; i < cols; j++) {
It looks like you mean j < cols here :)
Check line 76. When I compile and run the code, line 76 is where the exception is thrown.
This line specifically
arr[i][j] = n;
It seems your insertnumber() function is the culprit.

How to counting sort two dimensional array

Hi i have a problem with my code, i try sort array by counting sort (it must be stable sort), but my code doesn't work. I try implemented counting-sort from some wbesite, but it was in c# and I'm not sure s it done correctly. Can you tell me what is wrong with it?
#include <stdio.h>
#include <iostream>
using namespace std;
void sort_with_show(int **a, int rozmiar, int polecenie)
{
int y, d;
for (int i = 0; i< rozmiar - 1; i++)
{
for (int j = 0; j < rozmiar - 1 - i; j++)
{
if (a[j + 1][0] < a[j][0])
{
y = a[j][0];
a[j][0] = a[j + 1][0];
a[j + 1][0] = y;
}
}
}
for (int i = 0; i < rozmiar; i++)
{
//cout << tablica[i].x << " " << tablica[i].y << "\n";
if (polecenie == 0)
{
cout << a[i][0] << '\n';
}
else if (polecenie == 1)
{
cout << a[i][0] << "," << a[i][1] << "\n";
}
}
}
int main()
{
int rozmiar = 0;
int polecenie = 0;
char t[20] = { '\0' };
char *p, *q;
int liczba = 0;
int calaLiczba = 0;
bool isY = false;
cin >> rozmiar;
int ** a = new int *[rozmiar];
for (int i = 0; i < rozmiar; i++)
a[i] = new int[2];
cin.ignore();
int i = 0;
while(i < rozmiar)
{
fgets(t, sizeof t, stdin);
for (p = t, q = t + sizeof t; p < q; p++)
{
if (*p >= 48 && *p <= 57)
{
liczba = *p - 48;
calaLiczba = calaLiczba * 10 + liczba;
}
if (*p == ' ')
{
a[i][0] = calaLiczba;
isY = true;
calaLiczba = 0;
liczba = 0;
}
if (*p == '\n')
{
a[i][1] = calaLiczba;
isY = false;
}
}
for (int j = 0; j < 20; j++)
t[j] = '\0';
liczba = 0;
calaLiczba = 0;
isY = false;
i++;
}
cin >> polecenie;
cin.ignore();
sort_with_show(a, rozmiar, polecenie);
return 0;
}

c++ error: vector subscript out of range, line 1201

New to c++. I'm getting the "out of range" error message when try to debug the code. I tried to used resize(), but it is still not fixed. The code is to read instructions into a 2d vector and print out the graph.
What am I doing wrong?
#include<iostream>
#include<fstream>
#include<vector>
#include<string>
#include<sstream>
using namespace std;
typedef struct Pattern{
int rowNum;
int colNum;
char token;
bool isTriangular;
bool isOuter;
}Pattern;
void CommandProcessing(vector<string>&, Pattern&);
void Builder(Pattern&, vector<vector<char>>&);
void Printer(vector<vector<char>>&);
int main()
{
Pattern characters;
vector<vector<char>> key;
characters.colNum = 3;
characters.rowNum = 3;
characters.token = '#';
characters.isOuter = false;
characters.isTriangular = false;
Builder(characters, key);
Printer(key);
}
void Builder(Pattern& character, vector<vector<char>>& matrix)
{
int i = 0, j = 0;
char c;
if (character.token == 0)
c = 'a';
else
c = character.token;
matrix.resize(character.rowNum);
for (int i = 0; i < character.rowNum; i++){
if (character.isTriangular)
matrix[i].resize(i + 1);
else
matrix[i].resize(character.colNum);
if (character.isOuter)
{
if (character.isTriangular)
{
if (i = j)
matrix[i][j] = c;
else
matrix[character.rowNum - 1][i] = matrix[i][0] = c;
}
else
matrix[0][j] = matrix[i][0] = matrix[character.rowNum - 1][j] = matrix[i][character.colNum - 1] = c;
i++;
j++;
}
else
{
if (character.isOuter)
{
while (i <= j){
for (i = 0; i < character.rowNum; i++)
for (j = 0; i < character.colNum; j++)
matrix[i][j] = c;
}
}
else
for (i = 0; i < character.rowNum; i++)
for (j = 0; i < character.colNum; j++)
matrix[i][j] = c;
}
c++;
}
}
void Printer(vector<vector<char>>& print)
{
for (int i = 0; i < print.size(); i++){
for (int j = 0; j < print[i].size(); j++)
{
cout << print[i][j] << endl;
}
}
}
if (i = j) should be if (i == j).
if (i = j) do a assignment and test if i != 0.
Other problems:
while (i <= j){
for (i = 0; i < character.rowNum; i++)
for (j = 0; i < character.colNum; j++) // You test `i` instead of j
matrix[i][j] = c;
// Once test fixed
// Here `i == character.rowNum` and `j == character.colNum` (if `character.rowNum != 0`)
// So the while loop condition doesn't change and may so do infinite loop
}