eAthena - Adding 4 bytes to end of packet - c

I'm working on rewriting some source from eAthena. I need to add 4 bytes to the end of the packet. I'm trying to understand how. Wouldn't WFIFOL(sd->fd, len) = 0 add 4 bytes? Do I need to do a SWAP32 on this? Still learning thanks.
int clif_sendadditem(USER *sd, int num) {
char buf[128];
char buf2[128];
char *name = NULL;
char* owner = NULL;
int namelen;
int len;
int id;
//if(!sd->status.inventory[num].custom) {
id=sd->status.inventory[num].id;
//} else {
// id=sd->status.inventory[num].custom;
//}
if (id > 0 && !strcmpi(itemdb_name(id), "??")) {
memset(&sd->status.inventory[num], 0, sizeof(sd->status.inventory[num]));
return 0;
}
if (strlen(sd->status.inventory[num].real_name)) {
name = sd->status.inventory[num].real_name;
} else {
//if(!sd->status.inventory[num].custom) {
name = itemdb_name(id);
//} else {
// name = itemdb_namec(id);
//}
}
if (sd->status.inventory[num].amount > 1) {
sprintf(buf, "%s (%d)", name, sd->status.inventory[num].amount);
} else if(itemdb_type(sd->status.inventory[num].id)==ITM_SMOKE) {
//if(!sd->status.inventory[num].custom) {
sprintf(buf, "%s [%d %s]",name,sd->status.inventory[num].dura,itemdb_text(sd->status.inventory[num].id));
//} else {
// sprintf(buf, "%s [%d %s]",name,sd->status.inventory[num].dura,itemdb_textc(sd->status.inventory[num].custom));
//}
} else {
strcpy(buf, name);
}
namelen = strlen(buf);
if (!session[sd->fd])
{
session[sd->fd]->eof = 8;
return 0;
}
WFIFOHEAD(sd->fd, 255);
WFIFOB(sd->fd, 0) = 0xAA;
WFIFOB(sd->fd, 3) = 0x0F;
//WFIFOB(sd->fd, 4) = 0x03;
WFIFOB(sd->fd, 5) = num+1;
//if(!sd->status.inventory[num].custom) {
WFIFOW(sd->fd, 6) = SWAP16(itemdb_icon(id));
WFIFOB(sd->fd, 8) = itemdb_iconcolor(id);
//} else {
// WFIFOW(sd->fd, 6) = SWAP16(itemdb_iconc(id));
// WFIFOB(sd->fd, 8) = itemdb_iconcolorc(id);
//}
WFIFOB(sd->fd, 9) = namelen;
memcpy(WFIFOP(sd->fd, 10), buf, namelen);
len=namelen+1;
//if(!sd->status.inventory[num].custom) {
WFIFOB(sd->fd,len+9)=strlen(itemdb_name(id));
strcpy(WFIFOP(sd->fd,len+10),itemdb_name(id));
len+=strlen(itemdb_name(id))+1;
//} else {
// WFIFOB(sd->fd,len+9)=strlen(itemdb_namec(id));
// strcpy(WFIFOP(sd->fd,len+10),itemdb_namec(id));
// len+=strlen(itemdb_namec(id))+1;
//}
WFIFOL(sd->fd,len+9)=SWAP32(sd->status.inventory[num].amount);
len+=4;
if((itemdb_type(id)<3) || (itemdb_type(id)>17)) {
WFIFOB(sd->fd,len+9)=1;
WFIFOL(sd->fd,len+10)=0;
WFIFOB(sd->fd, len + 14) = 0;
len+=6;
} else {
WFIFOB(sd->fd,len+9)=0;
WFIFOL(sd->fd,len+10)=SWAP32(sd->status.inventory[num].dura);
WFIFOB(sd->fd, len + 14) = 0; //REPLACE WITH PROTECTED
len+=6;
}
if(sd->status.inventory[num].owner_id) {
owner=map_id2name(sd->status.inventory[num].owner_id);
WFIFOB(sd->fd,len+9)=strlen(owner);
strcpy(WFIFOP(sd->fd,len+10),owner);
len+=strlen(owner)+1;
FREE(owner);
} else {
WFIFOB(sd->fd,len+9)=0; //len of owner
len+=1;
}
//WFIFOW(sd->fd, len + 9) = SWAP16(0);
WFIFOW(sd->fd, 1) = SWAP16(len + 6);
WFIFOSET(sd->fd, encrypt(sd->fd));
return 0;
}

I was miscounting and changed the commented
//WFIFOW(sd->fd, len + 9) = SWAP16(0);
to
WFIFOL(sd->fd, len + 9) = SWAP32(0);
and then changed to len+10 at end

Related

How to setup stop condition on VEML7700 through I2C library? I am not getting the ACK from reading

int I2C_Master_ReadReg(unsigned char dev_addr, unsigned char reg_addr, unsigned char count, unsigned char *pData, void (* Sub)(void)) {
uint8_t cnt;
start();
sda(dev_addr);
if (!(dev_addr == 0x10)) {
cnt = 0;
}
if (count > 0x05) {
cnt = 0;
}
if (clk() == 1) {
I2C_Ack_Error(1);
return -1;
}
sda(reg_addr + 0);
if (clk() == 1) {
I2C_Ack_Error(2);
return -2;
}
start();
sda(dev_addr + 1);
if (clk() == 1) {
I2C_Ack_Error(3);
return -3;
}
for (cnt = 0; cnt < count; ++cnt) {
*(pData + cnt) = read();
//printf("D: %x\n\r", read());
if (clk() == 0) {
I2C_Ack_Error(4);
return -4;
}
stop();
}
return 0;
}

how can I read socket by blocking&none-multiplexing&sync mode?

I want to repeatedly request one specific url by maximum performance. I copied below source from github, but I think it isn't optimized for my case, so I have to tune it.
Which Option is best in my case?
block vs non-block
sync vs async
I think non-multiplexing is right, so I've to change select() function to the other one. Is this right?
char response[RESPONSE_SIZE + 1];
char *p = response, *q;
char *end = response + RESPONSE_SIZE;
char *body = 0;
enum {
length, chunked, connection
};
int encoding = 0;
int remaining = 0;
while (1) {
fd_set reads;
FD_ZERO(&reads);
FD_SET(server, &reads);
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 200;
if (FD_ISSET(server, &reads)) {
int bytes_received = SSL_read(ssl, p, end - p);
p += bytes_received;
*p = 0;
if (!body && (body = strstr(response, "\r\n\r\n"))) {
*body = 0;
body += 4;
printf("Received Headers:\n%s\n", response);
q = strstr(response, "\nContent-Length: ");
if (q) {
encoding = length;
q = strchr(q, ' ');
q += 1;
remaining = strtol(q, 0, 10);
} else {
q = strstr(response, "\nTransfer-Encoding: chunked");
if (q) {
encoding = chunked;
remaining = 0;
} else {
encoding = connection;
}
}
printf("\nReceived Body:\n");
}
if (body) {
if (encoding == length) {
if (p - body >= remaining) {
printf("%.*s", remaining, body);
break;
}
} else if (encoding == chunked) {
do {
if (remaining == 0) {
if ((q = strstr(body, "\r\n"))) {
remaining = strtol(body, 0, 16);
if (!remaining) goto finish;
body = q + 2;
} else {
break;
}
}
if (p - body >= remaining) {
printf("%.*s", remaining, body);
body += remaining + 2;
remaining = 0;
}
} while (!remaining);
}
} //if (body)
} //if FDSET
} //end while(1)
finish:
buffer[0] = '\0';
printf("\nClosing socket...\n");

string BUG in c project for school

I need to program a small airport management system for a school project and I have a terrible bug in my code.
As soon as I initialize the airportManager with more than one airport, all the IATA codes in the airports array get the name of the last airport that was input.
I have tried debugging it a lot of time but without any success. Everything is fine until I print the IATA code or use it. I will be glad for any help.
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define TEMP_STR_LEN 255
#define IATA_SIZE 3
// Airport struct:
struct Airport
{
char name[TEMP_STR_LEN];
char country[TEMP_STR_LEN];
char iata[IATA_SIZE];
} typedef airport;
// Airport functions:
int compareAirports(airport const *airport1, airport const *airport2)
{
if (strcmp(airport1->iata, airport2->iata) != 0)
return 0;
else
return 1;
}
int compareIataCode(airport *airport1, char const *iata)
{
if (strcmp(airport1->iata, iata) != 0)
return 0;
else
return 1;
}
void NameArrange(char *name)
{
char tmpString[255];
tmpString[0] = '\0';
char *token = strtok(name, " ");
int i, place = 0, strTotalLen = 0, lastTokenLen = 0;
while (token != NULL)
{
place++;
if (strlen(token) % 2 == 0)
{
for (i = 0; i < strlen(token) - 1; i++)
{
if (token[i] >= 'a' && token[i] <= 'z')
{
token[i] -= 32; // by ascii table
}
if ((token[i + 1] >= 'A' && token[i + 1] <= 'Z'))
token[i + 1] += 32; // by ascii table
i++;
}
}
else if (token[0] >= 'a' && token[0] <= 'z')
token[0] -= 32;
if (place != 1)
strcat(tmpString, " ");
strncat(tmpString, token, strlen(token));
strTotalLen += strlen(token);
lastTokenLen = strlen(token);
token = strtok(NULL, " ");
}
strTotalLen += (place - 1) * 2;
if (lastTokenLen % 2 != 0)
tmpString[strTotalLen - lastTokenLen] += 32;
strcpy(name, tmpString);
}
// ***Airport manager struct***
struct AirportManager
{
int airportsCount;
airport *airportArr;
} typedef airportMan;
// airportManager functions
void addAirport(airportMan *airportManager, airport *airportToAdd)
{
airportManager->airportArr = (airport *) realloc(airportManager->airportArr, (airportManager->airportsCount + 1) * (sizeof(airport)));
strcpy(airportManager->airportArr[airportManager->airportsCount].name, airportToAdd->name);
strcpy(airportManager->airportArr[airportManager->airportsCount].country, airportToAdd->country);
strcpy(airportManager->airportArr[airportManager->airportsCount].iata, airportToAdd->iata);
airportManager->airportsCount++;
printf(" BUG!!! %s\n", airportManager->airportArr[0].iata);
}
bool airportFind(airportMan *airportManager, char *iataCode)
{
int i;
printf("%s", airportManager->airportArr[0].iata );
char airportIata[IATA_SIZE];
char airportIata2[IATA_SIZE];
strcpy(airportIata, iataCode);
strcpy(airportIata2, airportManager->airportArr[0].iata);
if (strcmp(airportIata, airportIata2) == 0)
return true;
// for (i = 1; i < airportManager->airportsCount; i++) {
// printf("%s",airportManager->airportArr[0].iata );
// return true;
// }
puts("Airport not found");
return false;
}
bool checkDuplicatedIata(const airportMan *airportManger, const char *iata)
{
// checks if there is already airport with the same iata code as the input
int i;
for (i = 0; i < airportManger->airportsCount; i++)
{
if (compareIataCode(&(airportManger->airportArr[i]), iata))
{
puts("This IATA code is already exists, please try again");
return true;
}
}
return false;
}
bool checkIataSize(const char *iata)
{
if (strlen(iata) != IATA_SIZE)
{
puts("The IATA code must be 3 letters");
return false;
}
return true;
}
bool checkIataLetters(const char *iata)
{
// checks if all the letters in a given iata code are all capital
int i;
for (i = 0; i < strlen(iata); i++)
{
if (iata[i] >= 'a' && iata[i] <= 'z')
{
puts("The IATA code must be in capital letters");
return false;
}
}
return true;
}
bool checkIataOk(const char *iata, const airportMan *airportManager)
{
if (checkDuplicatedIata(airportManager, iata) == false
&& checkIataSize(iata) && checkIataLetters(iata))
return true;
else
return false;
}
airport *initAirport(airportMan *airportManager)
{
// asks the user to input an airport
airport *iniAirport;
iniAirport = (airport *) malloc(sizeof(airport));
char tmpStr[TEMP_STR_LEN];
char *ptr;
bool iataOk = false;
printf("please enter airport details (press enter to confirm):\nName:");
fflush(stdin);
fgets(tmpStr, 255, stdin);
if ((ptr = strchr(tmpStr, '\n')) != NULL)
*ptr = '\0';
strcpy(iniAirport->name, tmpStr);
NameArrange(iniAirport->name);
printf("Country:");
fgets(iniAirport->country, 255, stdin);
if ((ptr = strchr(iniAirport->country, '\n')) != NULL)
*ptr = '\0';
while (!iataOk)
{
printf("IATA code:");
fgets(iniAirport->iata, TEMP_STR_LEN, stdin);
fflush(stdin);
if ((ptr = strchr(iniAirport->iata, '\n')) != NULL)
*ptr = '\0';
iataOk = checkIataOk(iniAirport->iata, airportManager);
}
return iniAirport;
}
airportMan *initAirportManager()
{
airportMan *airportManager = (airportMan *) malloc(sizeof(airportMan));
if (airportManager == NULL)
return NULL;
airportManager->airportsCount = 0;
int airportsCount = 0, i = 0;
puts("Please enter how much airports you want to add");
scanf("%d", &airportsCount);
getchar();
for (i = 0; i < airportsCount; i++)
{
airport *airport = initAirport(airportManager);
addAirport(airportManager, airport);
}
return airportManager;
}
// ****Struct date*******
struct Date
{
int day;
int month;
int year;
} typedef date_t;
bool checkDateFormat(char *dateString)
{
char tmpString[TEMP_STR_LEN] = "";
strcpy(tmpString, dateString);
char *token = strtok(tmpString, "/");
if (strlen(token) == 2)
{
token = strtok(NULL, "/");
if (strlen(token) == 2)
{
token = strtok(NULL, "/");
if (strlen(token) == 4)
return true;
puts("Please enter the date in the correct format");
return false;
}
puts("Please enter the date in the correct format");
return false;
}
puts("Please enter the date in the correct format");
return false;
}
bool checkDate(date_t *date)
{
int daysArr[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (date->month > 0 && date->month <= 12)
{
if (date->day > 0 && date->day <= daysArr[date->month - 1])
{
if (date->year >= 2020)
return true;
puts("Invalid year, please try again");
return false;
}
puts("Invalid day, please try again");
return false;
}
puts("Invalid month, please try again");
return false;
}
date_t *initDate()
{
date_t *date;
char tmpDateString[TEMP_STR_LEN];
char *ptr;
bool checkFormat = false;
bool checkValid = false;
date = (date_t *) malloc(sizeof(date_t));
while ((!checkFormat) || (!checkValid))
{
puts("Please enter date in the following format: dd/mm/yyyy ");
fgets(tmpDateString, TEMP_STR_LEN, stdin);
if ((ptr = strchr(tmpDateString, '\n')) != NULL)
*ptr = '\0';
checkFormat = checkDateFormat(tmpDateString);
char *token = strtok(tmpDateString, "/");
date->day = atoi(token);
token = strtok(NULL, "/");
date->month = atoi(token);
token = strtok(NULL, "/");
date->year = atoi(token);
checkValid = checkDate(date);
}
return date;
}
// ***Flight struct***
struct Flight
{
char departureAirport[TEMP_STR_LEN];
char arrivalAirport[TEMP_STR_LEN];
int takeofTime;
date_t *date;
} typedef flight_f;
// ***flight functions
bool checkTakeOffTime(const flight_f *flight)
{
if ((flight->takeofTime >= 0 && flight->takeofTime <= 23))
return true;
puts("Invalid time");
return false;
}
bool compareFlightIata(const char *srcIata, const char *destIata)
{
return strcmp(srcIata, destIata) == 0;
}
bool compareFlightPath(const char *srcIata, const char *destIata)
{
if (compareFlightIata(srcIata, destIata))
{
puts("Flight must have different destination and source airports ");
return false;
}
return true;
}
flight_f *initFlight(airportMan *airportManager)
{
flight_f *flight;
char *ptr;
bool checkIata = false;
bool takeoffCheck = false;
bool airportExists = false;
flight = (flight_f *) malloc(sizeof(flight_f));
puts("Please enter flight details ");
while (!checkIata || !airportExists)
{
puts("\nSrc airport:");
fgets(flight->departureAirport, TEMP_STR_LEN, stdin);
if ((ptr = strchr(flight->departureAirport, '\n')) != NULL)
*ptr = '\0';
checkIata = (checkIataSize(flight->departureAirport)
&& checkIataLetters(flight->departureAirport));
if (checkIata)
airportExists = airportFind(airportManager, flight->departureAirport);
}
checkIata = false;
airportExists = false;
while (!checkIata || !airportExists)
{
puts("\nDec airport:");
fgets(flight->arrivalAirport, TEMP_STR_LEN, stdin);
if ((ptr = strchr(flight->arrivalAirport, '\n')) != NULL)
*ptr = '\0';
checkIata = (checkIataSize(flight->arrivalAirport)
&& checkIataLetters(flight->arrivalAirport)
&& compareFlightPath(flight->departureAirport,
flight->arrivalAirport));
if (checkIata)
airportExists = airportFind(airportManager, flight->arrivalAirport);
}
while (!takeoffCheck)
{
puts("\nTakeoff time: ");
scanf("%d", &flight->takeofTime);
getchar();
takeoffCheck = checkTakeOffTime(flight);
}
flight->date = initDate();
return flight;
}
bool checkFlightPath(flight_f flight, char const *departureFrom,
char const *arrivingTo)
{
if (strcmp(flight.departureAirport, departureFrom) == 0
&& strcmp(flight.arrivalAirport, arrivingTo) == 0)
return true;
else
return false;
}
int flightPathFind(flight_f **flightsArr, char const *departureFrom,
char const *arrivingTo, int size)
{
int count = 0;
int i;
for (i = 0; i < size; i++)
{
if (checkFlightPath((*flightsArr)[i], departureFrom, arrivingTo))
{
count++;
}
}
return count;
}
// Struct airline
struct Airline
{
char name[TEMP_STR_LEN];
int filghtsCount;
flight_f **flightsArr;
} typedef airline_a;
void addFlightToAirline(airline_a *airline, airportMan *airportManager)
{
airline->flightsArr = (flight_f **) realloc(airline->flightsArr,
(airline->filghtsCount + 1) * sizeof(flight_f *));
flight_f *flightToAdd = initFlight(airportManager);
airline->flightsArr[airline->filghtsCount] = flightToAdd;
airline->filghtsCount++;
}
void airlineFlightsCount(airline_a *airline, char const *departureFrom,
char const *arrivingTo)
{
int i;
int count = 0;
for (i = 0; i < airline->filghtsCount; i++)
{
if (checkFlightPath(*(airline->flightsArr[i]), departureFrom, arrivingTo))
count++;
}
printf("%s airline has %d flights in that path\n", airline->name, count);
}
airline_a *initAirline()
{
airline_a *airline;
airline = (airline_a *)malloc(sizeof(airline_a));
if (airline == NULL)
return NULL;
char *ptr;
puts("Please enter airline name:");
fgets(airline->name, TEMP_STR_LEN, stdin);
if ((ptr = strchr(airline->name, '\n')) != NULL)
*ptr = '\0';
airline->filghtsCount = 0;
airline->flightsArr = NULL;
return airline;
}
int main()
{
airportMan *airportManager = initAirportManager();
return 0;
}

find the line which causes the segmentation fault, which I couldn't find

Currently I am writing a LZ77 algorithm. When I try to run my code, for some reason I get the ZSH segmentation fault. I've searched some topics but I couldn't find where to fix my code for this.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
/*#define pencereBoyutu 60
#define bufferBoyutu 40*/
typedef enum { false, true } bool;
// ============================================================================
int ortakBul(unsigned char window[], unsigned char str[], int strLen) {
int j, k, yer = -1;
int pencereBoyutu = 60;
for (int i = 0; i <= pencereBoyutu - strLen; i++) {
yer = k = i;
for (j = 0; j < strLen; j++) {
if (str[j] == window[k])
k++;
else
break;
}
if (j == strLen)
return yer;
}
return -1;
}
// ============================================================================
int compress(char* inputPath) {
FILE *fileInput;
FILE *fileOutput;
bool last = false;
int girisUzunlugu = 0;
int cikisUzunlugu = 0;
int setSonu = 0;
int yer = -1;
int i, size, shift, c_in;
size_t bytesRead = (size_t) -1;
int arrayBoyutu = 100;
int pencereBoyutu = 60;
int bufferBoyutu = 40;
unsigned char c;
unsigned char array[arrayBoyutu];
unsigned char window[pencereBoyutu];
unsigned char buffer[bufferBoyutu];
unsigned char bufferYukle[bufferBoyutu];
unsigned char str[bufferBoyutu];
// input out açmak
char path[30] = "";
strcat(path, inputPath);
fileInput = fopen(path, "rb");
fileOutput = fopen("output/output.lz77", "wb");
// mümkün değilse error ver
if (!fileInput) {
fprintf(stderr, "fileInput acilamiyor. %s", inputPath);
return 0;
}
// fileinput uzunluğunu çek
fseek(fileInput, 0, SEEK_END);
girisUzunlugu = ftell(fileInput);
fseek(fileInput, 0, SEEK_SET);
fprintf(stdout, "Giris dosyasi boyutu: %d byte", girisUzunlugu);
// dosya boşsa hata ver
if (girisUzunlugu == 0)
return 3;
// eğer dosya boyutu arrayboyutundan düşükse hata ver
if (girisUzunlugu < arrayBoyutu)
return 2;
// arrayı byte olarak oku
fread(array, 1, arrayBoyutu, fileInput);
fwrite(array, 1, pencereBoyutu, fileOutput);
// LZ77 mantığı
while (true) {
if ((c_in = fgetc(fileInput)) == EOF)
last = true;
else
c = (unsigned char) c_in;
for (int k = 0; k < pencereBoyutu; k++)
window[k] = array[k];
for (int k = pencereBoyutu, j = 0; k < arrayBoyutu; k++, j++) {
buffer[j] = array[k];
str[j] = array[k];
}
// en uzun ortak kelimeyi bulmak
if (setSonu != 0) {
size = bufferBoyutu - setSonu;
if (setSonu == bufferBoyutu)
break;
}
else {
size = bufferBoyutu;
}
yer = -1;
for (i = size; i > 0; i--) {
yer = ortakBul(window, str, i);
if (yer != -1)
break;
}
// hiç ortak bulunmaması halinde
if (yer == -1) {
fputc(255, fileOutput);
fputc(buffer[0], fileOutput);
shift = 1;
}
// ortak bulunması halinde
else {
fputc(pencereBoyutu - yer, fileOutput);
fputc(i, fileOutput);
if (i == bufferBoyutu) {
shift = bufferBoyutu + 1;
if (!last)
fputc(c, fileOutput);
else
setSonu = 1;
}
else {
if (i + setSonu != bufferBoyutu)
fputc(buffer[i], fileOutput);
else
break;
shift = i + 1;
}
}
// Shift buffer
for (int j = 0; j < arrayBoyutu - shift; j++)
array[j] = array[j + shift];
if (!last)
array[arrayBoyutu - shift] = c;
if (shift == 1 && last)
setSonu++;
if (shift != 1) {
// yeni bitler oku
bytesRead = fread(bufferYukle, 1, (size_t) shift - 1, fileInput);
// yeni bitleri arraya yükle
for (int k = 0, l = arrayBoyutu - shift + 1; k < shift - 1; k++, l++)
array[l] = bufferYukle[k];
if (last) {
setSonu += shift;
continue;
}
if (bytesRead < shift - 1)
setSonu = shift - 1 - bytesRead;
}
}
// fileoutput uzunluğunu çek
fseek(fileOutput, 0, SEEK_END);
cikisUzunlugu = ftell(fileOutput);
fseek(fileOutput, 0, SEEK_SET);
fprintf(stdout, "\nCikis dosya boyutu: %d byte\n", cikisUzunlugu);
// I/O dosyaları kapanması
fclose(fileInput);
fclose(fileOutput);
return 1;
}
// ============================================================================
// Decompress
int decompress() {
FILE *fileInput;
FILE *fileOutput;
int shift, denge, ortak, c_in;
bool done = false;
int pencereBoyutu = 60;
int bufferBoyutu = 40;
int arrayBoyutu = pencereBoyutu + bufferBoyutu;
unsigned char c;
unsigned char window[pencereBoyutu];
unsigned char writeBuffer[pencereBoyutu];
unsigned char readBuffer[2];
// i/o dosyalarin acilmasi
fileInput = fopen("output/output.lz77", "rb");
fileOutput = fopen("output/file", "wb");
if (!fileInput) {
fprintf(stderr, "fileInput açılamıyor. %s", "output.lz77");
return 0;
}
fread(window, 1, pencereBoyutu, fileInput);
fwrite(window, 1, pencereBoyutu, fileOutput);
// decompress mantığı
while (true) {
size_t bytesRead = fread(readBuffer, 1, 2, fileInput);
if (bytesRead >= 2) {
denge = (int) readBuffer[0];
ortak = (int) readBuffer[1];
if (denge == 255) {
denge = 0;
c = (unsigned char) ortak;
ortak = 0;
shift = ortak + 1;
}
else {
shift = ortak + 1;
c_in = fgetc(fileInput);
if (c_in == EOF)
done = true;
else
c = (unsigned char) c_in;
}
for (int i = 0, j = pencereBoyutu - denge; i < ortak; i++, j++)
writeBuffer[i] = window[j];
fwrite(writeBuffer, 1, (size_t) ortak, fileOutput);
if (!done)
fputc(c, fileOutput);
// Shift window
for (int i = 0; i < pencereBoyutu - shift; i++)
window[i] = window[i + shift];
for (int i = 0, j = pencereBoyutu - shift; i < ortak; i++, j++)
window[j] = writeBuffer[i];
window[pencereBoyutu - 1] = c;
}
else {
break;
}
}
// dosyaları kapat
fclose(fileInput);
fclose(fileOutput);
return 1;
}
// ============================================================================
int main(int argc, char* argv[]) {
clock_t begin = clock();
if (argc < 2) {
printf("2 argüman gerekiyor: [-c|-d] [dosya_yolu]");
} else {
// decompress
if (strcmp(argv[1], "-d") == 0) {
int result = decompress();
if (result == 0) {
fprintf(stderr, "\nSikistirma islemi HATALI");
} else if (result == 1) {
printf("\nSikistirma islemi OK");
}
}
// compress
else if (strcmp(argv[1], "-c") == 0) {
int result = compress(argv[2]);
if (result == 0) {
fprintf(stderr, "\nSikistirma islemi HATALI\n");
} else if (result == 1) {
printf("\nSikistirma islemi OK");
} else if (result == 2) {
fprintf(stderr, "\nDosya cok kucuk.\n");
} else if (result == 3) {
fprintf(stderr, "\nDosya bos.\n");
}
} else {
printf("Gecersiz argumanlar.");
}
}
// calistirma zamanını bastırmak
clock_t end = clock();
printf("\n\nCalistirma zamani: ");
printf("%f", ((double) (end - begin) / CLOCKS_PER_SEC));
printf(" [saniye]");
return 0;
}
// ============================================================================
After compiling you have to give arguments for running:
./lz77 -c input.txt
when I try to run my application with the input above which has 100 characters in it, it gives me segmentation fault. I couldn't find any reason after done some research about it. I'll be so happy if anyone can help.

Why am I getting this message in hackerrank "~ no response on stdout ~"? I don't know what I am missing>

Why am I getting this message in hackerrank "~ no response on stdout ~"? I don't know what I am missing?
I am bit frustrated right now because I have no clue about what to do.
So I was left with only choice to post this query on Stackoverflow.
Here is the link to the problem
Here is my complete code:
char* readline();
// Complete the countingValleys function below.
int countingValleys(int n, char* s)
{
int dwnhl = 0, level = 0;
bool frmsurface = true;
int k = strlen(s);
for (int i = 0; i < k; i++)
{
if (level == 0)
{
frmsurface = true;
}
if (s[i] == 'D')
{
level--;
if ((level < 0) && (frmsurface == true))
{
dwnhl++;
frmsurface = false;
//printf("went downhill %d ",i);
}
}
else if (s[i] == 'U')
{ //printf("went uphill %d ",i);
level++;
}
// printf("\nhello - %c",s[i]);
}
printf("\nNumber of downhill = %d \n", dwnhl);
return (dwnhl);
}
int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
char* n_endptr;
char* n_str = readline();
int n = strtol(n_str, &n_endptr, 10);
if (n_endptr == n_str || *n_endptr != '\0')
{
exit(EXIT_FAILURE);
}
char* s = readline();
int result = countingValleys(n, s);
printf("%d\n", result);
return 0;
}
char* readline()
{
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true)
{
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line)
{
break;
}
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n')
{
break;
}
size_t new_length = alloc_length << 1;
data = realloc(data, new_length);
if (!data)
{
break;
}
alloc_length = new_length;
}
if (data[data_length - 1] == '\n')
{
data[data_length - 1] = '\0';
}
data = realloc(data, data_length);
return data;
}
One problem is the way you handle frmsurface
The first time you enter the loop frmsurface is set to true. If the events are UUDD, your code will still count a "valley" because you don't clear frmsurface when you go up.
Instead of
if(level==0)
{
frmsurface=true;
}
you could try:
frmsurface = (level == 0);
but I don't really understand why you want the boolean. Just test for level == 0 instead. Something like:
if(s[i]=='D')
{
if(level==0)
{
dwnhl++;
}
level--;
}
else if (s[i]=='U')
{
level++;
}
Also I wonder if this line:
printf("\nNumber of downhill = %d \n", dwnhl);
must be removed.
Notice that
int k=strlen(s);
for(int i=0;i<k;i++)
could probably just be
for(int i=0;i<n;i++)
^
as n is passed to the function

Resources