Pass array pointer to other program and extract that pointer in c - pointers

I am trying to pass an array of integer to other program and accept that from *argv. Then sort the array and print that from initial program. But I can not accept the pointer of the array and work with it. (can't even compile sort.c)
#include<stdio.h>
int main(int argc, char *argv[])
{
int arr = argv[1];
int temp = 0;
int length = sizeof(arr);
//Sort the array in descending order
for (int i = 0; i < length; i++) {
for (int j = i+1; j < length; j++) {
if(arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
int length = args-1;
int arr[length];
for(int i=0;i<length,i++)
{
arr[i]=argv[i+1];
}
int *p=arr
pid_t pid=fork();
if (pid==0) {
execv("sort",p);
}
else {
}
return 0;
}

Related

Freeing an array of pointer but heap block

I wrote a program that has to read a 2D array from a text file and save it into a double pointer which will act as a 2D array.
Here's the code :
#include <stdio.h>
#include <stdlib.h>
char **create_map(char* filename);
int n;
int m;
char **map;
int main(int argc, char* argv[]) {
int i;
map = create_map(argv[1]);
for(i = 0; i < n; i++) {
free(map[i]);
}
free(map);
return 0;
}
char **create_map(char *filename) {
int i = 0;
char *row;
char **map;
FILE *file = fopen(filename, "r");
fscanf(file, "%d %d", &n, &m);
map = malloc(sizeof(char *) * n);
row = malloc(sizeof(char)*m);
while(fscanf(file, "%s\n", row) != EOF) {
map[i] = malloc(sizeof(char)*m);
strcpy(map[i], row);
i++;
}
free(map[9]);
free(row);
fclose(file);
return map;
}
The content of the file is stored successfully in the map variable, but when it comes to freeing some space the debugger prints "warning: Heap block at 0000029967AF5770 modified at 0000029967AF578A past requested size of a".
Why the memory can't be freed?
Where's the error?
Thank you in advance.

Qt application crash when trying to delete Qimage Format_RGB888

I get a "HEAP CORRUPTION DETECTED: After normal block ... CRT detected that the application wrote to memory after end of heap buffer." when variable test gets destroyed.
If I change the image size, the crash does not occur, I'm thinking it has something to do with memory alignment, but I cannot figure out what.
I am using the official Qt builds for MSVC 2017 64bit
#include <QCoreApplication>
#include <QImage>
QImage foo(int width, int height)
{
QImage retVal(width, height, QImage::Format_RGB888);
for (int i = 0; i < height; ++i) // read each line of the image
{
QRgb *lineBuf = reinterpret_cast<QRgb *>(retVal.scanLine(i));
for (int j = 0; j < width; ++j)
{
lineBuf[j] = qRgb(0,0,0);
}
}
return retVal;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
{
QImage test = foo(5,5);
}
return a.exec();
}
As GM suggested in the comment above, the problem is that QRgb is a 32bit construct.
I've changed the code replacing QRgb with a custom RGB struct
struct RGB {
uint8_t r;
uint8_t g;
uint8_t b;
};
QImage foo(int width, int height)
{
QImage retVal(width, height, QImage::Format_RGB888);
for (int i = 0; i < height; ++i) // read each line of the image
{
RGB *lineBuf = reinterpret_cast<RGB *>(retVal.scanLine(i));
for (int j = 0; j < width; ++j)
{
RGB tmp;
//.... do stuff with tmp
lineBuf[j] = tmp;
}
}
return retVal;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
{
QImage test = foo(5,5);
}
return a.exec();
}

Finding the number of occurence of all the permutations of a SubString in a String in C

Basically this program is made up of two other programs.
First Part to find the permutations of a Sub-String and the
Second Part to find the number of occurence of all the permutations in a given String.
I'm not Getting the required output for most cases
I'd be glad if anybody could help.Thanks.
Here is the Program..
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int appearanceCount(int input1,int input2,char* input3,char* input4)
{
int count=0,temp,i,j,k;
int no_of_permutations=1;
for(i=1;i<input1+1;i++)
{
no_of_permutations *= i;
}
int a = no_of_permutations/((input1-1));
for (i=0; i < a; i++)
{
for(j=0; j<input1-1; j++)
{
char temp;
temp=input3[j];
input3[j]=input3[j+1];
input3[j+1] = temp;
//printf("\n%s",input3);
char *temp_input4 = input4;
//Now I have got the permutation
//Finding the occurance
while(temp_input4 = (strstr(temp_input4, input3)) )
{
count++;
printf("\n%s -- %s -- %d",temp_input4,input3,count);
temp_input4++;
}
}
}
return count;
}
int main()
{
int output = 0;
int ip1;
scanf("%d", &ip1);
int ip2;
scanf("%d", &ip2);
char* ip3;
ip3 = (char *)malloc(512000 * sizeof(char));
scanf("\n%[^\n]",ip3);
char* ip4;
ip4 = (char *)malloc(512000 * sizeof(char));
scanf("\n%[^\n]",ip4);
output = appearanceCount(ip1,ip2,ip3,ip4);
printf("\n%d", output);
return 0;
}
My Expected output for the values
4
11
cAda
AbrAcadAbRa
would be
2
because the two possible sequence that can be found in the string are Acad and cadA
but I get the output as 0;
Try using anagram search and then it will work fine.

Error connecting server and client programs

I wrote those two codes. server and client.
//***Server***
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <WinSock2.h>
#define BUF_SIZE 1024
#define OPSZ 4
void ErrorHandling(char *message);
int calculate(int opnum, int opnds[], char op);
int main(int argc, char *argv)
{
WSADATA wsaData;
SOCKET hServSock, hClntSock;
char opinfo[BUF_SIZE];
int result, opndCnt, i;
int recvCnt, recvLen;
SOCKADDR_IN servAdr, clntAdr;
int clntAdrSize;
if(argc != 2)
{
printf("Usage : %s <port>\n", argv[0]);
exit(1);
}
if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
ErrorHandling("WSAStartup() error!");
hServSock = socket(PF_INET, SOCK_STREAM, 0);
if(hServSock == INVALID_SOCKET)
ErrorHandling("socket() error");
memset(&servAdr, 0, sizeof(servAdr));
servAdr.sin_family = AF_INET;
servAdr.sin_addr.s_addr = htonl(INADDR_ANY);
servAdr.sin_port = htons(atoi((char*)argv[1]));
if(bind(hServSock, (SOCKADDR*)&servAdr, sizeof(servAdr)) == SOCKET_ERROR)
ErrorHandling("bind() error");
if(listen(hServSock, 5) == SOCKET_ERROR)
ErrorHandling("listen() error");
clntAdrSize = sizeof(clntAdr);
for(i=0; i<5; i++)
{
opndCnt = 0;
hClntSock = accept(hServSock, (SOCKADDR*)&clntAdr, &clntAdrSize);
recv(hClntSock, (char*)&opndCnt, 1, 0);
recvLen = 0;
while((opndCnt*OPSZ+1) > recvLen)
{
recvCnt = recv(hClntSock, &opinfo[recvLen], BUF_SIZE-1, 0);
recvLen += recvCnt;
}
result = calculate(opndCnt, (int*)opinfo, opinfo[recvLen-1]);
send(hClntSock, (char*)&result, sizeof(result), 0);
closesocket(hClntSock);
}
closesocket(hServSock);
WSACleanup();
return 0;
}
int calculate(int opnum, int opnds[], char op)
{
int result = opnds[0], i;
switch(op)
{
case '+':
for(i=1; i<opnum; i++) result += opnds[i];
break;
case '-':
for(i=1; i<opnum; i++) result -= opnds[i];
break;
case '*':
for(i=1; i<opnum; i++) result *= opnds[i];
break;
}
return result;
}
void ErrorHandling(char *message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
//***client***
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <WinSock2.h>
#define BUF_SIZE 1024
#define RLT_SIZE 4
#define OPSZ 4
void ErrorHandling(char *message);
int main(int argc, char *argv[])
{
WSADATA wsaData;
SOCKET hSocket;
char opmsg[BUF_SIZE];
int result, opndCnt, i;
SOCKADDR_IN servAdr;
if(argc != 3)
{
printf("Usage : %s <IP> <port>\n", argv[0]);
exit(1);
}
if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
ErrorHandling("WSAStartup() error!");
hSocket = socket(PF_INET, SOCK_STREAM, 0);
if(hSocket == INVALID_SOCKET)
ErrorHandling("socket() error");
memset(&servAdr, 0, sizeof(servAdr));
servAdr.sin_family = AF_INET;
servAdr.sin_addr.s_addr = inet_addr(argv[1]);
servAdr.sin_port = htons(atoi(argv[2]));
if(connect(hSocket, (SOCKADDR*)&servAdr, sizeof(servAdr)) == SOCKET_ERROR)
ErrorHandling("connect() error!");
else
puts("Connected..........");
fputs("Operand count: ", stdout);
scanf("%d", &opndCnt);
opmsg[0] = (char)opndCnt;
for(i=0; i<opndCnt; i++)
{
printf("Operand %d: ", i+1);
scanf("%d", (int*)&opmsg[i*OPSZ+1]);
}
fgetc(stdin);
fputs("Operator: ", stdout);
scanf("%c", &opmsg[opndCnt*OPSZ+1]);
send(hSocket, opmsg, opndCnt*OPSZ+2, 0);
recv(hSocket, (char*)&result, RLT_SIZE, 0);
printf("Operation result: %d \n", result);
closesocket(hSocket);
WSACleanup();
return 0;
}
void ErrorHandling(char *message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
I compiled those two codes (that means 2 projects separately) and that made Debug folder.
I saved those 2 project folders to Desktop.
I started cmd and then wrote
cd Desktop-> cd server -> cd Debug -> server 9190
but the error happens (I first coded server to turn the server on, and then I was planning to make the connection between the server and client.)
int main(int argc, char *argv) should read int main(int argc, char **argv)
char *argv[] would also work.
What does int argc, char *argv[] mean? might be worth a read.
Here is a link to a tutorial that will help you get started with winsock programming.

Qt Error segmentation fault when trying to show window

I have a class ClientWindow. I have created several instances of it and appended the their pointers to a a list. If i try to show any of the windows however, I get "Segmentation fault (core dumped)" I keep the list of windows in a class called controller.
Here is my controller header file:
#ifndef CONTROLLER_H
#define CONTROLLER_H
#include "clientwindow.h"
class Controller
{
public:
Controller();
void createClients(int num);
void showWindows();
private:
QList<ClientWindow*> clWList;
int size;
};
#endif // CONTROLLER_H
this is the cpp file:
#include "controller.h"
Controller::Controller()
{
}
void Controller::createClients(int num)
{
size = num;
for(int i = 0; i < size; i++)
{
ClientWindow cw;
clWList.append(&cw);
}
}
void Controller::showWindows()
{
for(int i = 0; i < size; i++)
{
ClientWindow* cw = clWList.at(0);
cw->show();
}
}
this is my main:
#include <QtGui/QApplication>
#include "clientwindow.h"
#include "controller.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// ClientWindow w;
// w.show();
QString temp = argv[1];
bool ok;
int tempI = temp.toInt(&ok, 10);
Controller c;
c.createClients(tempI);
c.showWindows();
return a.exec();
}
This is where it goes wrong:
for(int i = 0; i < size; i++)
{
ClientWindow cw;
clWList.append(&cw);
}
A local variable cw is created on the stack in each iteration. It is deallocated at the end of each iteration. Meaning the data is gone. So you end up storing pointers pointing to junk.
Calling a member function of a junk typically results in crash. :) Do this instead:
for(int i = 0; i < size; i++)
{
ClientWindow * cw = new ClientWindow();
clWList.append(cw);
}
You'll have to go through the list and delete the objects after you are done with them.

Resources