lundi 30 mars 2015

Unsolved Quiz Shortest code



That s a test, follows code,you have to insert the shortest correction into the space without touching anything away from it /* TO BE DONE START / / TO BE DONE END */ that makes those two files give the same output


The shortest code has to be less than 80 characters counting the "/* TO BE DONE START // TO BE DONE END */" string


hello0.c



#include <stdio.h>
#include <stdlib.h>
#include <string.h>

my_printf(char*p){
char s[strlen(p)+1];
strcpy(s,p);

/*** TO BE DONE START ***//*** TO BE DONE END ***/

}

main(){
my_printf("hello world!");
my_printf("How are you?");
my_printf("i\'m OK, and you?");
my_printf("1, 2, 3, testing ...");
my_printf("bye bye!");
exit(0);
}


hello1.c



#include <stdio.h>
#include <stdlib.h>
main(){
printf("Hello world!\n");
printf("How are you?\n");
printf("I\'m OK, and you?\n"
"1, 2, 3, testing ...\n"
"Bye bye!\n");
exit(0);
}



Datatype of pthread_t in pthreads?



I have a code in 32 bit in which int is used in place of pthread_t ? so while porting do i need to change to long in LP64 (64 bit). What is the datatype of pthread_t ?




DB2, to check size on C procedures



When defining a procedure like this:



create or replace procedure xxx.name
(in table_name varchar(6)
,in key_columns varchar(3000)
)
external name 'lib.so-VERSION!LIBNNN'
language c
parameter style sql
modifies sql data
commit on return no
program type sub;


Do I need to check the size of the input inside the C implementation of the procedure (so that I dont't risk buffer overflows)? ...Is there an error before the C code is invoked? I cannot run my own tests so any help is appreciated!




Good C-coding style for multiple lines if conditions



I am programming a project in C and have a problem: I've got a lot of if conditions and it might get really hard for other people to read. I haven't yet found a similar question on the internet.


Do you have an idea or example how to make my code more readable?


Here is the C Code:



if( ((g_cycle_cnt == uartTxSecondaryMsg[3][msgPos[3]].sliceNo) || //correct slicenumber...
(uartTxSecondaryMsg[3][msgPos[3]].sliceNo == -1) || // or as fast as possible...

( (uartTxSecondaryMsg[3][msgPos[3]].sliceNo == -2) &&
((uartTxSecondaryMsg[3][msgPos[3]].timeFrameBegin>=g_uptime_cnt) &&
(uartTxSecondaryMsg[3][msgPos[3]].timeFrameEnd<=g_uptime_cnt)))) &&

((dataProcessingFlag & SECONDARY_MSG_ANNOUNCED_CH4) == SECONDARY_MSG_ANNOUNCED_CH4) )



c - fix unknown register name ‘%xmm1’ in ‘asm’?



i am trying to build a project for ubuntu 14.04 X86 and I've got the following error:



error: unknown register name ‘%xmm1’ in ‘asm’
asm volatile (
^
error: unknown register name ‘%xmm0’ in ‘asm’
error: unknown register name ‘%mm1’ in ‘asm’
error: unknown register name ‘%mm0’ in ‘asm’
error: unknown register name ‘%xmm0’ in ‘asm’
asm volatile (
^
error: unknown register name ‘%mm0’ in ‘asm’
asm volatile (


in function :



static inline void
hev_bytes_xor_sse (guint8 *data, gsize size, guint8 byte)
{
gsize i = 0, c = 0, p128 = 0, p64 = 0;
guint64 w = (byte << 8) | byte;

asm volatile (
"movq %0, %%mm0\t\n"
"pshufw $0x00, %%mm0, %%mm1\t\n"
"movq2dq %%mm1, %%xmm0\t\n"
"pshufd $0x00, %%xmm0, %%xmm1\t\n"
::"m"(w)
:"%mm0", "%mm1", "%xmm0", "%xmm1"
);


gcc version 4.8.2




ncurses mvaddch() cursor movement not as expected



Code:



#include <ncurses.h>

int main(int argc, char **argv)
{
initscr();
noecho();
cbreak();


mvprintw(0, 0, curses_version());
mvprintw(1, 0, "Hello World");
mvaddch(2, 0, mvinch(1, 4)); // Why doesn't this work?

getch();
endwin();

return 0;


}


Output:



ncurses 5.9.20130608
Hello World


with pointer blinking (waiting for getch ) just after o of Hello.


Question:

As in C, arguments passed to a function are evaluated first before calling that function, mvinch() will be called first and when it'll return the character o the call to mvaddch() will be made.

But then why character o is not printed on line 2 (just below Hello World)? Instead mvaddch prints o at current cursor position (thanks to winch which is 1,4). Here mvaddch() behaves just like addch paying no respect to the mv prefix and the explicit movement coordinates given to it. Why?


Is this a possible bug in mvaddch() or am I missing something?




Xorshift pseudorandom number generator with shiftvalues in progmem



I started implementing a xor shift generator. To safe some RAM I tried to put the shiftvalues into the PROGMEM but this actually does make some "strange" results and i dont know why. It seems that it returns the same value for a long time, than get back to regular expected results.


I hope you can help me and show me what I have done wrong.



const uint8_t shift[] PROGMEM =
{
0x01, 0x01, 0x02, 0x01, 0x01, 0x03, 0x01, 0x07, 0x03, 0x01, 0x07, 0x06, 0x01, 0x07, 0x07, 0x02, 0x01, 0x01,
0x02, 0x05, 0x05, 0x03, 0x01, 0x01, 0x03, 0x01, 0x05, 0x03, 0x05, 0x04, 0x03, 0x05, 0x05, 0x03, 0x05, 0x07,
0x03, 0x07, 0x01, 0x04, 0x05, 0x03, 0x05, 0x01, 0x03, 0x05, 0x03, 0x06, 0x05, 0x03, 0x07, 0x05, 0x05, 0x02,
0x05, 0x05, 0x03, 0x06, 0x03, 0x05, 0x06, 0x07, 0x01, 0x07, 0x03, 0x05, 0x07, 0x05, 0x03, 0x07, 0x07, 0x01
}; //needed as hex

static uint8_t y8 = 13;
static uint8_t cur_shift = 0, request_count = 0;

uint8_t rnd()
{
//shift the shifting numbers
request_count++;
if(request_count == 255)
{
request_count = 0;
cur_shift++;
if (cur_shift == 24)
{
cur_shift = 0;
}
}
//shift something around
y8 ^= (y8 << pgm_read_byte(&(shift[cur_shift * 3])));
y8 ^= (y8 >> pgm_read_byte(&(shift[cur_shift * 3 + 1])));
return y8 ^= pgm_read_byte(&(shift[cur_shift * 3 + 2]));
}


Reference to the Numbers for the shift




find preorder given postorder and inorder



it is the code of uva 536 http://ift.tt/19njc3i


But I want to ask,if the questions changes, that means asking preorder given postorder and inorder, how can i change my code???any one helps?it is urgent,thanks(NOT A HOMEWORK)



#include <stdio.h>
#include <string.h>
char inorder[100], preorder[100];
char line[200];
void trace(int ihead, int itail, int phead, int ptail)
{
char split = preorder[phead];
int i;
int len;
if (ihead > itail) return;
for (i=ihead; inorder[i] != split; ++i) ;
len = i - ihead;
trace(ihead, i-1, phead+1, phead+len);
len = itail - i - 1;
trace(i+1, itail, ptail - len, ptail);
printf("%c", split);
}
int main() {
int n;
for (;;) {
if (gets(line) == NULL) break;
sscanf(line, "%s %s", preorder, inorder);
n = strlen(inorder);
trace(0, n-1, 0, n-1);
printf("\n");}
return 0;
}



GetProcessAffinityMask returns null process affinity



In a very simple test console application, I tried to get process' affinity mask:



#include <cstdlib>
#include <cstdio>
#include <windows.h>

int main()
{
while (1)
{
DWORD dwProcessAffinityMask = 0;
DWORD dwSystemAffinityMask = 0;

BOOL res = GetProcessAffinityMask(
GetCurrentProcess(),
(PDWORD_PTR)&dwProcessAffinityMask,
(PDWORD_PTR)&dwSystemAffinityMask);

printf("%d 0x%X 0x%X\n",
res,
dwProcessAffinityMask,
dwSystemAffinityMask);

Sleep(1000);
}

return 0;
}


Here is the output (64-bit executable, 64-bit system, meaning I do not fall into the WoW64 special case):



1 0x0 0x3
1 0x0 0x3
...


Running on my laptop, which has a 2 cores CPU, the resulting system's mask looks correct. But I don't understand the meaning of the dwProcessAffinityMask value I get here. Just for the sake of it, I also tried to toy around with the Task Manager by changing the process' affinity mask but the output remains the same.


This behavior doesn't seem to be documented.




C++ Passing user input to a parameter for a constructors



Here is in C++ Passing user input to a variable to a parameter for a function in. But I need pass parameters from user for constructor parameters. Please help me with simple example. Don't have to be same as mine, you can do all different but I just need it.



#include <iostream>
#include <cmath>

using namespace std;

float stockMarketCalculator(float p, float r, int t){
float a;

for(int day = 1; day <=t; day++){
a = p * pow(1+r, day);
cout << a << endl;
}

}

int main()
{
float p;
float r;
int t;

cout << "Please enter the principle" << endl;
cin >> p >> endl;

cout << "Please enter the rate" << endl;
cin >> r >> endl;

cout << "Please enter the time in days" << endl;
cin >> t >> endl;
cout << stockMarketCalculator(p, r, t);

return 0;
}



C assembler function casting



I came across this piece of code (for the whole program see this page, see the program named "srop.c").


My question is regarding how func is used in the main method. I have only kept the code which I thought could be related.


It is the line *ret = (int)func +4; that confuses me.


There are three questions I have regarding this:



  1. func(void) is a function, should it not be called with func() (note the brackets)

  2. Accepting that that might be some to me unknown way of calling a function, how can it be casted to an int when it should return void?

  3. I understand that the author doesn't want to save the frame pointer nor update it (the prologue), as his comment indicates. How is this skipping-two-lines ahead achieved with casting the function to an int and adding four?


.



(gdb) disassemble func
Dump of assembler code for function func:
0x000000000040069b <+0>: push %rbp
0x000000000040069c <+1>: mov %rsp,%rbp
0x000000000040069f <+4>: mov $0xf,%rax
0x00000000004006a6 <+11>: retq
0x00000000004006a7 <+12>: pop %rbp
0x00000000004006a8 <+13>: retq
End of assembler dump.


Possibly relevant is that when compiled gcc tells me the following:

warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]


Please see below for the code.



void func(void)
{
asm("mov $0xf,%rax\n\t");
asm("retq\n\t");
}

int main(void)
{
unsigned long *ret;

/*...*/

/* overflowing */
ret = (unsigned long *)&ret + 2;
*ret = (int)func +4; //skip gadget's function prologue

/*...*/

return 0;
}



Error in my switch case



So I'm trying to make an input function That takes in things separated by a comma and puts each thing into it's own array. I think I almost have it figured with this switch, but it gets stuck in the second statement. I don't know why.



/*************************************************************************

3/25/2015
This program takes in a file of the format
PART,2.000,-1,0.050,V
PART,0.975,-1,0.025,V
PART,3.000,+1,0.010,F
GAP,0.000,0.080
does the tolerance analysis
**************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#define BUFFER_SIZE 1024
#define ARRAYSIZE 100
void input(char *gapPart, float *nom,float *tollerance,int *SIGNS,char *V_F,float Spec_Minnimum,float Spec_Maximum);
void toleracningPt1(int size, char gapPart[], float nom[],float tollerance[],int SIGNS[],char V_F[],float Spec_Minnimum,float Spec_Maximum);
int main(){
/**Decs**/
float nom[ARRAYSIZE]; //holds the nominal values (2.00, .975 ect)
float tollerance[ARRAYSIZE]; //holds the third value (.05, .025, ect)
int SIGNS[ARRAYSIZE]; // signifies if the value goes up or down
char gapPart[ARRAYSIZE];// holds the value if it's a gap or part
char V_F[ARRAYSIZE]; // F things cannot be changed, V things can be
int size=0;
float Spec_Minnimum=0, Spec_Maximum=0;
/**custom functions**/
input(gapPart, nom, tollerance, SIGNS, V_F, Spec_Minnimum, Spec_Maximum);
toleracningPt1(size, gapPart,nom, tollerance, SIGNS, V_F, Spec_Minnimum, Spec_Maximum);
return 0;
}
/***********************************************************************************************************/
void input(char *gapPart,float *nom,float *tollerance,int *SIGNS,char *V_F,float Spec_Minnimum,float Spec_Maximum){

const char *delimiterCharacters = " ";
const char *delimiterCharacters2 = ",";
const char *filename = "tin.txt";
FILE *inputFile = fopen( filename, "r" );
char buffer[ BUFFER_SIZE ];
char *lastToken;
int i=1, step;

printf("File Data\n");
/* usual error check*/
if(inputFile == NULL ){
fprintf( stderr, "Unable to open file %s\n", filename );
}else{
/**Prints out contents of the file **/
while( fgets(buffer, BUFFER_SIZE,inputFile) != NULL ){// while there is stuff to do this with
lastToken = strtok( buffer, delimiterCharacters );
while( lastToken != NULL ){//same song..
printf( "%s\n", lastToken );
lastToken = strtok( NULL, delimiterCharacters );// clear out lastToken
}

}

rewind(inputFile);

while( fgets(buffer, BUFFER_SIZE,inputFile) != NULL ){// while there is stuff to do this with
lastToken = strtok( buffer, delimiterCharacters2 );
while( lastToken != NULL ){//same song..
//strtok into seperate arrays
while(i=1,i<5,++i){
switch(i){
case 1:
fscanf(inputFile,"%s\n", &gapPart[i]);
printf("debug1");
++i;
break;
case 2:
printf("debug2");
fscanf(inputFile,"%f\n", &nom[i]);
++i;
break;
case 3:
printf("debug3");
fscanf(inputFile,"%d\n", &SIGNS[i]);
++i;
break;
case 4:
printf("debug4");
fscanf(inputFile,"%f\n", &tollerance[i]);
break;
case 5:
printf("debug5");
fscanf(inputFile,"%c\n", &V_F[i]);
break;
default:
printf("Error");
}
}


}
lastToken = strtok( NULL, delimiterCharacters2 );// clear out lastToken
}
}



fclose(inputFile );

}


/*****************************************************************************************************************/
void toleracningPt1(int size, char gapPart[], float nom[],float tollerance[],int SIGNS[],char V_F[],float Spec_Minnimum,float Spec_Maximum)
{
int x;
float Act_Gap, Act_Tollerance, Maximum_Gap = 0.0, Minnimum_Gap = 0.0;
for ( x=0, Act_Gap = 0; x<size; x++){ //does tolerance math
Act_Gap = Act_Gap + (nom[x]*SIGNS[x]);
}
for ( x=0, Act_Tollerance = 0; x<size; x++){
Act_Tollerance = Act_Tollerance + (tollerance[x]);
}
for (x= 0, Maximum_Gap = 0; x<size; x++){
Maximum_Gap = (nom[x]*SIGNS[x]+tollerance[x])+Maximum_Gap;
Minnimum_Gap = (nom[x]*SIGNS[x]-tollerance[x])+Minnimum_Gap;
}

printf("Actual Gap Mean: %.3f\"\n", Act_Gap); //printing
printf("Actual Gap Tolerance: %.3f\"\n", Act_Tollerance);
if (Maximum_Gap > Spec_Maximum){
printf("The maximum gap (%.3f\") is (Greater) than specified (%.3f\")\n", Maximum_Gap, Spec_Maximum);
}
if (Maximum_Gap < Spec_Maximum){
printf("The maximum gap (%.3f\") is (Less) than specified (%.3f\")\n", Maximum_Gap, Spec_Maximum);
}
if (Minnimum_Gap > Spec_Minnimum){
printf("The minimum gap (%.3f\") is (Greater) than specified (%.3f\")\n", Minnimum_Gap, Spec_Minnimum);
}
if (Minnimum_Gap < Spec_Minnimum){
printf("The minimum gap (%.3f\") is (Less) than specified (%.3f\")\n", Minnimum_Gap, Spec_Minnimum);
}
}



using fork function after getting user's input



How do you get the fork function to work after getting the user's input from the fgets() function and getting tokens from the user's input?


My code:



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>

/* the line can have at most 2000 words*/
void tokeniseLine(char *Line, char **Words, int *Wordn);

/* break line into words separated by whitespace, placing them in the
array words, and setting the count to Wordn */

void search&execute();

int main()
{
char Line[4000], *Words[2000], string[4000];
int Stops=0,Wordn=0;
char *end = "exit";

while(1)
{
printf("Enter program: ");
fgets(Line, 4000, stdin ); /* read a line of text here */

/* use of exitting begins when user enters 'exit' or when the program finally locates/can't locate the user's requested file*/
if ( strcmp(Line, end) == 0 ){
exit(0);
}
else
if ( strcmp(Line, end) != 0 ) {
printf("file successfully found.");
tokeniseLine(Line,Words,&Wordn);
search&execute();//using fork function to make process
}
return 0;
}

void tokeniseLine(char *Line, char **Words, int *Wordn)
{
char *token;

/* get the first token */
token = strtok(Line, " \t\n");

/* walk through other tokens */
while( token != NULL )
{
token = strtok(NULL, " \t\n");
}
return;
}

void search&execute()//this is the function which I wanted to work last after the user input is tokenised
{
pid_t childpid; /* variable to store the child's pid */
int retval; /* child process: user-provided return code */
int status; /* parent process: child's exit status */

/* only 1 int variable is needed because each process would have its
own instance of the variable
here, 2 int variables are used for clarity */

/* now create new process */
childpid = fork();

if (childpid >= 0) /* fork succeeded */
{
if (childpid == 0) /* fork() returns 0 to the child process */
{
printf("CHILD: I am the child process!\n");
printf("CHILD: Here's my PID: %d\n", getpid());
printf("CHILD: My parent's PID is: %d\n", getppid());
printf("CHILD: The value of my copy of childpid is: %d\n",childpid);
printf("CHILD: Sleeping for 1 second...\n");
sleep(1); /* sleep for 1 second */
printf("CHILD: Enter an exit value (0 to 255): ");
scanf(" %d", &retval);
printf("CHILD: Goodbye!\n");
exit(retval); /* child exits with user-provided return code */
}
else /* fork() returns new pid to the parent process */
{
printf("PARENT: I am the parent process!\n");
printf("PARENT: Here's my PID: %d\n", getpid());
printf("PARENT: The value of my copy of childpid is %d\n",childpid);
printf("PARENT: I will now wait for my child to exit.\n");
wait(&status); /* wait for child to exit, and store its status */
printf("PARENT: Child's exit code is: %d\n", WEXITSTATUS(status));
printf("PARENT: Goodbye!\n");
exit(0); /* parent exits */
}
}
else /* fork returns -1 on failure */
{
perror("fork"); /* display error message */
exit(0);
}


}


I tried to have the fork function to return the fork value, but it doesn't work when I tried to add in user input. How do you fix that?




Getline in loop consuming constantly more memory in embedded linux



After running application over weekend I noticed in the morning that it was killed because no memory was left.


After commenting some parts of code, I see that this procedure might be a problem, but I can't figure out why.



void readData (char * path) {

// Reading and parsing config from file
FILE * fp;
size_t len = 0;
size_t read;

char *begin, *end, line[100], data[100];

fp = fopen(path, "r");
if (fp != NULL)
{
while ((read = getline(&line, &len, fp)) != -1) {
/* begin = strstr(line, "\"data\":[")+8;
end = strstr(begin, "]");
strncpy(data, begin,strlen(begin) - strlen(end));
data[strlen(begin) - strlen(end)] = 0;
*/
int tmp;

// sscanf(data,"%d,%d,%d,%d,%d,%d",&tmp,&ss.tensionRaw,&tmp,&tmp,&ss.depthRaw,&ss.speedRaw);
ss.tension = cs.tensionCoeff * ss.tensionRaw;
ss.speed = cs.speedCoeff * ss.speedRaw;
ss.depth = cs.depthCoeff * ss.depthRaw;

/* begin = strstr(line, "\"failedRequests\":\"")+18;
end = strstr(begin, "\"");
strncpy(data, begin,strlen(begin) - strlen(end));
data[strlen(begin) - strlen(end)] = 0;
ss.connectionOK = atoi(data);*/
}
}
fclose(fp);
}


Can getline cause problems like this? I monitor memory use of app by "top" and every 15-20 sec it gets around 4K more. When i comment whole while loop, it's not increasing.




Inserting an element in a list without tail or head



I've got a little problem about an exercice which is supposed to explain how malloc works.


For starters, here's the header we have been given:



struct cell_m
{
unsigned int magicnumber ;
struct cell_m *next ;
void *userspacestart ;
void *userspacestop ;
};

typedef struct cell_m *liste_t ;


As you can see, i have only a next pointer so it's a simple chained list. I am supposed to code a function to insert a cell_m inside a liste_t of cell_m. There is one condition, the size of the cell_m that we want to insert must be smaller than the one we're currently at. Here's my code of this function :



void insert(liste_t *list, liste_t cell)
{
liste_t *old_list = malloc(sizeof(liste_t*));

if (sizeof((*list)->userspacestop) - (sizeof((*list)->userspacestart))
>= (sizeof(cell->userspacestop)) - (sizeof(cell->userspacestart)))
/*insert at the begining*/
else
{
old_list = list;
(*list) = (*list)->next;
while ((*list)->next != NULL)
{
if (sizeof((*list)->userspacestop) - (sizeof((*list)->userspacestart))
>= (sizeof(cell->userspacestop)) - (sizeof(cell->userspacestart)))
{
(*old_list)->next = cell;
cell->next = (*list);
break;
}
old_list = list;
(*list) = (*list)->next;
}
}
}


A little explanation : I try to keep the last position of where i was in the list so i created an "old_list" variable to keep it. At first, i try to see if i can directly insert my cell at the beginning of the list. I'm not entirely sure what to put here so i put a comment for now. Then, if it's not possible to insert it at the begining, i move forward into my list and try to insert the element. (then again, not entirely sure if the code for inserting is right)


Is this any good or am i totally wrong with this code? Thank you !




c++ int array with values of 2 dimension int array (3d array)



I'm trying to make an array which contain int[][] items


i.e



int version0Indexes[][4] { {1,2,3,4} , {5,6,7,8 , }
int version1Indexes[][4] { ...... }

int version15Indexes[][4] {... }


(total of 16)



int indexes[][][] = { version0Indexes,version1Indexes, .. }


anyone can suggest how to do so ?


Thanks




C structure for SPI 24-bit address device



I am communicating with an SPI Audio record IC which has 24-bit address and 16-bit offset. I made a structure to read/write data from that device which has,


Command - 1 byte Address - 3 byte (24-bit) Offset address - 2 byte (16-bit)


During simulation (in proteous), it is found that 4th byte (MSB of address) is overlapped by 5th byte (LSB of Offset).


Following is the code. Please help what are the changes I need to do in the code.



typedef struct {
unsigned char Command:8 ;
unsigned long Addr:24;
unsigned int Offset:16;
} ISD_Struct;
ISD_Struct ISD_Rec;
void main()
{
address = 0x563412 ;
OFFST = 0x9A78 ;
ISD_Rec.Command = 0xBC;
ISD_Rec.Addr = address;
ISD_Rec.Offset = OFFST;
Write_SPI(&ISD_Rec,6); //sending (1byte command + 3byte address + 2 byte offset)
//Delay_ms(1000);
}


Thanks




How to monitor file modifications and know what changes were made



I'm working on a Java project where I need to monitor files in a certain directory and be notified whenever changes are made on one of the files, this can be achieved using WatchService. Furthermore, I want to know what changes were made, for example: "characters 10 to 15 where removed", "at index 13 characters 'abcd' were added"... I'm willing to take any solution even based on c language monitiring the fileSystem. I also want to avoid the diff solution to avoid storing the same file 2 times, and for the complexity of the algorithm, it takes to much time for big files. Thank you for help. :)




Passing information between textbox and program source code



So I have myself a project with two files in it, AT.c and main.c (I use DEV-C++). AT.c contains all the calculation stuff I need, uses command line for I/O and works relatively fine by itself. However, since I need a GUI for the program, I also got the main.c file, which basically creates a window with textboxes for me to put the numbers in.


Anyway, now I'm kinda stuck because I have no idea how to make AT.c read values from those textboxes instead of using the scanf method. I suppose I should probably make some declarations or links between the two codes, but I haven't found anything that could help yet.


The code is main.c is the starting one you get when creating a new windows application project in Dev-C++. I only altered the LRESULTCALLBACK part.



#define ID_BUTTON 1
#define ID_TEXTBOX 2

static HWND hwndA;
static HWND hwndB;
/* This function is called by the Windows function DispatchMessage() */


LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message) /* handle the messages */
{
case WM_CREATE:{
CreateWindow(TEXT("Button"), TEXT("Generate"),
WS_CHILD | WS_VISIBLE,
10, 160, 80, 20,
hwnd, (HMENU) ID_BUTTON, NULL, NULL
);
hwndA = CreateWindow(TEXT("EDIT"), TEXT(""),
WS_VISIBLE | WS_CHILD | WS_BORDER,
190, 130, 70, 15,
hwnd, (HMENU) ID_TEXTBOX, NULL, NULL
);
hwndB = CreateWindow(TEXT("EDIT"), TEXT(""),
WS_VISIBLE | WS_CHILD | WS_BORDER,
260, 130, 70, 15,
hwnd, (HMENU) ID_TEXTBOX, NULL, NULL
);
break;
}
case WM_COMMAND:{

if (LOWORD(wParam) == ID_BUTTON) {
char wot[256];

GetWindowText(hwndA, wot, 4);
SetWindowText(hwndB, wot);
}
}

break;
}
case WM_DESTROY:
PostQuitMessage (0); /* send a WM_QUIT to the message queue */
break;
default: /* for messages that we don't deal with */
return DefWindowProc (hwnd, message, wParam, lParam);
}

return 0;
}


The AT.c is just big, yet very simple calculating program. Like



#include<stdio.h>
#include<stdlib.h>
#include<math.h>

int a, b, c;

main(){
scanf("%d", &a);
scanf("%d", &b);
printf("\n%d", a+b);
system("pause");
}


just with bunch of ifs and loops.




encode h264 video using ffmpeg library memory issues



I'm trying to do screen capture on OS X using ffmpeg's avfoundation library. I capture frames from the screen and encode it using H264 into an flv container.


Here's the command line output of the program:



Input #0, avfoundation, from 'Capture screen 0':
Duration: N/A, start: 9.253649, bitrate: N/A
Stream #0:0: Video: rawvideo (UYVY / 0x59565955), uyvy422, 1440x900, 14.58 tbr, 1000k tbn, 1000k tbc
raw video is inCodec
FLV (Flash Video)http://localhost:8090/test.flv
[libx264 @ 0x102038e00] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX
[libx264 @ 0x102038e00] profile High, level 4.0
[libx264 @ 0x102038e00] 264 - core 142 r2495 6a301b6 - H.264/MPEG-4 AVC codec - Copyleft 2003-2014 - http://ift.tt/1cmqH4m - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=6 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=1 weightp=2 keyint=50 keyint_min=5 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=abr mbtree=1 bitrate=400 ratetol=1.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
[tcp @ 0x101a5fe70] Connection to tcp://localhost:8090 failed (Connection refused), trying next address
[tcp @ 0x101a5fe70] Connection to tcp://localhost:8090 failed: Connection refused
url_fopen failed: Operation now in progress
[flv @ 0x102038800] Using AVStream.codec.time_base as a timebase hint to the muxer is deprecated. Set AVStream.time_base instead.
encoded frame #0
encoded frame #1
......
encoded frame #49
encoded frame #50
testmee(8404,0x7fff7e05c300) malloc: *** error for object 0x102053e08: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
(lldb) bt
* thread #10: tid = 0x43873, 0x00007fff95639286 libsystem_kernel.dylib`__pthread_kill + 10, stop reason = signal SIGABRT
* frame #0: 0x00007fff95639286 libsystem_kernel.dylib`__pthread_kill + 10
frame #1: 0x00007fff9623742f libsystem_pthread.dylib`pthread_kill + 90
frame #2: 0x00007fff977ceb53 libsystem_c.dylib`abort + 129
frame #3: 0x00007fff9ab59e06 libsystem_malloc.dylib`szone_error + 625
frame #4: 0x00007fff9ab4f799 libsystem_malloc.dylib`small_malloc_from_free_list + 1105
frame #5: 0x00007fff9ab4d3bc libsystem_malloc.dylib`szone_malloc_should_clear + 1449
frame #6: 0x00007fff9ab4c877 libsystem_malloc.dylib`malloc_zone_malloc + 71
frame #7: 0x00007fff9ab4b395 libsystem_malloc.dylib`malloc + 42
frame #8: 0x00007fff94aa63d2 IOSurface`IOSurfaceClientLookupFromMachPort + 40
frame #9: 0x00007fff94aa6b38 IOSurface`IOSurfaceLookupFromMachPort + 12
frame #10: 0x00007fff92bfa6b2 CoreGraphics`_CGYDisplayStreamFrameAvailable + 342
frame #11: 0x00007fff92f6759c CoreGraphics`CGYDisplayStreamNotification_server + 336
frame #12: 0x00007fff92bfada6 CoreGraphics`display_stream_runloop_callout + 46
frame #13: 0x00007fff956eba07 CoreFoundation`__CFMachPortPerform + 247
frame #14: 0x00007fff956eb8f9 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 41
frame #15: 0x00007fff956eb86b CoreFoundation`__CFRunLoopDoSource1 + 475
frame #16: 0x00007fff956dd3e7 CoreFoundation`__CFRunLoopRun + 2375
frame #17: 0x00007fff956dc858 CoreFoundation`CFRunLoopRunSpecific + 296
frame #18: 0x00007fff95792ef1 CoreFoundation`CFRunLoopRun + 97
frame #19: 0x0000000105f79ff1 CMIOUnits`___lldb_unnamed_function2148$$CMIOUnits + 875
frame #20: 0x0000000105f6f2c2 CMIOUnits`___lldb_unnamed_function2127$$CMIOUnits + 14
frame #21: 0x00007fff97051765 CoreMedia`figThreadMain + 417
frame #22: 0x00007fff96235268 libsystem_pthread.dylib`_pthread_body + 131
frame #23: 0x00007fff962351e5 libsystem_pthread.dylib`_pthread_start + 176
frame #24: 0x00007fff9623341d libsystem_pthread.dylib`thread_start + 13


I've attached the code I used below.



#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#include <libavdevice/avdevice.h>
#include <libavutil/opt.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>

// void show_av_device() {

// inFmt->get_device_list(inFmtCtx, device_list);
// printf("Device Info=============\n");
// //avformat_open_input(&inFmtCtx,"video=Capture screen 0",inFmt,&inOptions);
// printf("===============================\n");
// }

void registerLibs() {
av_register_all();
avdevice_register_all();
avformat_network_init();
avcodec_register_all();
}

int main(int argc, char *argv[]) {

//conversion variables
struct SwsContext *swsCtx = NULL;
//input stream variables
AVFormatContext *inFmtCtx = NULL;
AVCodecContext *inCodecCtx = NULL;
AVCodec *inCodec = NULL;
AVInputFormat *inFmt = NULL;
AVFrame *inFrame = NULL;
AVDictionary *inOptions = NULL;
const char *streamURL = "http://localhost:8090/test.flv";
const char *name = "avfoundation";

// AVFrame *inFrameYUV = NULL;
AVPacket inPacket;


//output stream variables
AVCodecContext *outCodecCtx = NULL;
AVCodec *outCodec = NULL;
AVFormatContext *outFmtCtx = NULL;
AVOutputFormat *outFmt = NULL;
AVFrame *outFrameYUV = NULL;
AVStream *stream;

int i, videostream, ret;
int numBytes, frameFinished;

registerLibs();
inFmtCtx = avformat_alloc_context(); //alloc input context
av_dict_set(&inOptions, "pixel_format", "uyvy422", 0);
av_dict_set(&inOptions, "probesize", "7000000", 0);

inFmt = av_find_input_format(name);
ret = avformat_open_input(&inFmtCtx, "Capture screen 0:", inFmt, &inOptions);
if (ret < 0) {
printf("Could not load the context for the input device\n");
return -1;
}
if (avformat_find_stream_info(inFmtCtx, NULL) < 0) {
printf("Could not find stream info for screen\n");
return -1;
}
av_dump_format(inFmtCtx, 0, "Capture screen 0", 0);
// inFmtCtx->streams is an array of pointers of size inFmtCtx->nb_stream

videostream = av_find_best_stream(inFmtCtx, AVMEDIA_TYPE_VIDEO, -1, -1, &inCodec, 0);
if (videostream == -1) {
printf("no video stream found\n");
return -1;
} else {
printf("%s is inCodec\n", inCodec->long_name);
}
inCodecCtx = inFmtCtx->streams[videostream]->codec;
// open codec
if (avcodec_open2(inCodecCtx, inCodec, NULL) > 0) {
printf("Couldn't open codec");
return -1; // couldn't open codec
}


//setup output params
outFmt = av_guess_format(NULL, streamURL, NULL);
if(outFmt == NULL) {
printf("output format was not guessed properly");
return -1;
}

if((outFmtCtx = avformat_alloc_context()) < 0) {
printf("output context not allocated. ERROR");
return -1;
}

printf("%s", outFmt->long_name);

outFmtCtx->oformat = outFmt;

snprintf(outFmtCtx->filename, sizeof(outFmtCtx->filename), streamURL);
printf("%s\n", outFmtCtx->filename);

stream = avformat_new_stream(outFmtCtx, outCodec);
outCodecCtx = stream->codec;

outCodecCtx->codec_id = CODEC_ID_H264;
outCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
outCodecCtx->flags = CODEC_FLAG_GLOBAL_HEADER;
outCodecCtx->width = inCodecCtx->width;
outCodecCtx->height = inCodecCtx->height;
outCodecCtx->time_base.den = 25;
outCodecCtx->time_base.num = 1;
outCodecCtx->pix_fmt = AV_PIX_FMT_YUV420P;
outCodecCtx->gop_size = 50;
outCodecCtx->bit_rate = 400000;

if (avio_open(&outFmtCtx->pb, outFmtCtx->filename, AVIO_FLAG_READ_WRITE ) < 0) {
perror("url_fopen failed");
}



if (avformat_write_header(outFmtCtx, NULL) != 0) {
printf("was not able to write header to outout format");
return -1;
}


numBytes = avpicture_get_size(PIX_FMT_UYVY422, inCodecCtx->width, inCodecCtx->height);
// Allocate video frame
inFrame = av_frame_alloc();

swsCtx = sws_getContext(inCodecCtx->width, inCodecCtx->height, inCodecCtx->pix_fmt, inCodecCtx->width,
inCodecCtx->height, PIX_FMT_YUV420P, SWS_BILINEAR, NULL, NULL, NULL);
int frame_count = 0;
while(av_read_frame(inFmtCtx, &inPacket) >= 0) {
if(inPacket.stream_index == videostream) {
avcodec_decode_video2(inCodecCtx, inFrame, &frameFinished, &inPacket);
// 1 Frame might need more than 1 packet to be filled
if(frameFinished) {
outFrameYUV = av_frame_alloc();

uint8_t *buffer = (uint8_t *)av_malloc(numBytes*sizeof(uint8_t));

int ret = avpicture_fill((AVPicture *)outFrameYUV, buffer, PIX_FMT_YUV420P,
inCodecCtx->width, inCodecCtx->height);
if(ret < 0){
printf("%d is return val for fill\n", ret);
return -1;
}
//convert image to YUV
sws_scale(swsCtx, (uint8_t const * const* )inFrame->data,
inFrame->linesize, 0, inCodecCtx->height,
outFrameYUV->data, outFrameYUV->linesize);
//outFrameYUV now holds the YUV scaled frame/picture

AVPacket pkt;
int got_output;
av_init_packet(&pkt);
pkt.data = NULL;
pkt.size = 0;

outFrameYUV->pts = frame_count;

ret = avcodec_encode_video2(outFmtCtx->streams[0]->codec, &pkt, outFrameYUV, &got_output);
if (ret < 0) {
fprintf(stderr, "Error encoding video frame: %s\n", av_err2str(ret));
return -1;
}

if(got_output) {
if(stream->codec->coded_frame->key_frame) {
pkt.flags |= AV_PKT_FLAG_KEY;
}
pkt.stream_index = stream->index;
if(pkt.pts != AV_NOPTS_VALUE)
pkt.pts = av_rescale_q(pkt.pts, stream->codec->time_base, stream->time_base);
if(pkt.dts != AV_NOPTS_VALUE)
pkt.dts = av_rescale_q(pkt.dts, stream->codec->time_base, stream->time_base);
avio_open_dyn_buf(&outFmtCtx->pb);
ret = av_interleaved_write_frame(outFmtCtx, &pkt);
unsigned char *pb_buffer;
int len = avio_close_dyn_buf(outFmtCtx->pb, (unsigned char **)&pb_buffer);
avio_write(outFmtCtx->pb, (unsigned char *)pb_buffer, len);

} else {
ret = 0;
}
if(ret != 0) {
fprintf(stderr, "Error while writing video frame: %s\n", av_err2str(ret));
exit(1);
}

fprintf(stderr, "encoded frame #%d\n", frame_count);
frame_count++;

av_free_packet(&pkt);
av_free(outFrameYUV);
av_free(inFrame);

}
}
av_free_packet(&inPacket);
}
av_write_trailer(outFmtCtx);

//close video stream
if(stream) {
avcodec_close(outCodecCtx);
}
for (i = 0; i < outFmtCtx->nb_streams; i++) {
av_freep(&outFmtCtx->streams[i]->codec);
av_freep(&outFmtCtx->streams[i]);
}
if (!(outFmt->flags & AVFMT_NOFILE))
/* Close the output file. */
avio_close(outFmtCtx->pb);
/* free the output format context */
avformat_free_context(outFmtCtx);

// Free the YUV frame populated by the decoder
av_free(inFrame);

// Close the video codec (decoder)
avcodec_close(inCodecCtx);

// Close the input video file
avformat_close_input(&inFmtCtx);

return 1;


I'm not sure what I've done wrong here. But, what I've observed is that for each frame thats been encoded, my memory usage goes up by about 6MB. Backtracking afterward usually leads one of the following two culprits:



  1. avf_read_frame function in avfoundation.m

  2. av_dup_packet function in avpacket.h


Can I also get advice on the way I'm using avio_open_dyn_buff function to be able to stream over http? I've also attached my ffmpeg library versions below:



ffmpeg version N-70876-g294bb6c Copyright (c) 2000-2015 the FFmpeg developers
built with Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)
configuration: --prefix=/usr/local --enable-gpl --enable-postproc --enable-pthreads --enable-libmp3lame --enable-libtheora --enable-libx264 --enable-libvorbis --disable-mmx --disable-ssse3 --disable-armv5te --disable-armv6 --disable-neon --enable-shared --disable-static --disable-stripping
libavutil 54. 20.100 / 54. 20.100
libavcodec 56. 29.100 / 56. 29.100
libavformat 56. 26.101 / 56. 26.101
libavdevice 56. 4.100 / 56. 4.100
libavfilter 5. 13.101 / 5. 13.101
libswscale 3. 1.101 / 3. 1.101
libswresample 1. 1.100 / 1. 1.100
libpostproc 53. 3.100 / 53. 3.100
Hyper fast Audio and Video encoder



Open a socket with the name socket:[4023]



I'm working on a linux system and want to open a socket for IPC. The process ID of the process I want to communicate with is 123. The process already opened the socket. I know that it is possible to send the file descriptor via unix domain sockets or dbus. But:


Is there also a way to open the socket by the name gotten from /proc/123/fd/15 ? If I call “ls -l” in /proc/123/fd/ the symlink looks like “15 -> socket:[4023]”. Is there a way to open “socket:[4023]” ?


Edit: I am tried to do this in C.


Regards, Maz




Get function assembly code from GCC



Now I encounter problem. My project works on assembly-level. So I need assembly-level programming but the project scale is too large to do work on assembly-level only. Because of this issue, I determine get binary code(of assembly-code) from c-source-file made by gcc. but how? How can I get binary code(of assembly-code) from gcc?


I have a idea,



write(fd, (char *)function_name, sizeof(function_name))


but It's not good way to solve this problem, It would make me need to handle many file when I need many function as target.


Is there other good way to solve this problem? I think ideal solution that need only function name(and output file name if needed) and works on command-line. Is ideal solution which I think impossible?




Receiving "Control may reach end of non-void function"



The output should allow the user to enter his/her taxable income then choose a filing status then receive his/her tax due. When I try to run, I receive "control may reach end of non-void function" at the end bracket of each function such as float single's end bracket.



#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

void taxableincome (float *TI)
{
printf("Enter your taxable income ");
scanf("%f", &*TI);
}

float single (float TI)
{
if (TI > 0 && TI <=24000)
return .15 * TI;
if (TI > 24000 && TI <= 58150)
return 3600 + .28 * (TI - 24000);
if (TI > 58150 && TI <= 121300)
return 13162.00 + .31 * (TI - 58150);
if (TI > 121300 && TI <= 263750)
return 32738.50 + .36 * (TI - 121300);
if (TI < 263750)
return 84020.50 + .396 * (TI - 263750);
}

float marriedfilingjointly (float TI)
{
if (TI > 0 && TI <= 40100)
return .15 * TI;
if (TI > 40100 && TI <= 96900)
return 6015 + .28 * (TI - 40100);
if (TI > 96900 && TI <= 147700)
return 21919.00 + .31 * (TI - 96900);
if (TI > 147700 && TI <= 263750)
return 37667.00 + .36 * (TI - 14770);
if (TI > 263750)
return 79445.00 + .396 * (TI - 263750);
}

float marriedfilingseperately (float TI)
{
if (TI > 0 && TI <=20050)
return .15 + TI;
if (TI > 20050 && TI <= 48450)
return 3007.50 + .28 * (TI - 20050);
if (TI > 48450 && TI <= 73850)
return 10959.50 + .31 * (TI - 48450);
if (TI > 73850 && TI <= 131875)
return 18833.50 + .36 * (TI - 73850);
if (TI > 131875)
return 39722.50 + .396 * (TI - 131875);
}

float headofhouse (float TI)
{
if (TI > 0 && TI <=32150)
return .15 + TI;
if (TI > 32150 && TI <= 83050)
return 4822.50 + .28 * (TI - 23150);
if (TI > 83050 && TI <= 134500)
return 19074.50 + .31 * (TI - 83050);
if (TI > 134500 && TI <= 263750)
return 35024.00 + .36 * (TI - 134500);
if (TI > 263750)
return 81554.00 + .396 * (TI - 263750);
}

void menu (float TI)
{
int filingstatus;
printf("Enter filing status\n");
printf("1. Single\n");
printf("2. Married Filing Jointly\n");
printf("3. Married Filing Seperately\n");
printf("4. Head of House\n");
scanf("&d", &filingstatus);

switch (filingstatus)
{
case 1: printf("Total due tax for single filing: %f\n", single(TI));
break;
case 2: printf("Total due tax for married and filing jointly: %f\n", marriedfilingjointly(TI));
break;
case 3: printf("Total due tax for married but filing seperatedly : %f\n", marriedfilingseperately(TI));
break;
case 4: printf("Total due tax for head of house filing: %f\n", headofhouse(TI));
break;
default:printf("Invalid\n");
}
}

void main ()
{
int filingstatus;
float TI;
taxableincome (&TI);
menu (TI);
}



Stack based allocation not recommended?



The libmemcached documentation has this note:



You may wish to avoid using memcached_create(3) or memcached_clone(3) with a stack based allocation. The most common issues related to ABI safety involve heap allocated structures.



How do I have to understand it? Stands in this case ABI for Application Binary Interface? I would like to provide the pointer to the struct for memcached_clone() from a variable in the local function scope. Is it safe?


Example - is this code OK?



foo()
{
memcached_st clone_memc;

memcached_clone(&clone_memc, master_memc);

// some memcache function calls (get/set)
...

memcached_free(&clone_memc);
}



How the getcwd is implemented in the kernel (library)?



One process could do



chdir("/to/some/where");


when from the another shell



mv /to/some/where /now/different/path/


the 1st process



print getcwd();
#prints /now/different/path/


How the getcwd is implemented? (at the lowest level, e.g. at the level of kernel, inodes ...).




How to disable/enable HDIM on Raspberry Pi



So I can use "tvservice -o" to turn off the HDMI on the raspberry Pi, and "tvservice -p" to turn it back on. After turning it back on I apparently need to do "fbset -depth 8 && fbset -depth 16" to re-enable the frame buffer and then force an X11 redraw.


My question is, how do I do this in C? I have an X11 application and I can manage the X11 redraw no problem, but how do I disable/re-enable HDMI in C, and how do I re-enable the frame buffer after re-enabling HDMI?


To give background, I have a headless application running as a sort of media server, controlled by an Android app. Currently I am permanently disabling the turning off of HDMI after a timeout. However to save energy I would like to disable the HDMI when the app is not in use, and then turn it back on and display the RPi application on screen using libcec to determine when the TV is using the RPi's HDMI connection to turn HDMI on and off.




Implementing a Linked List C



I am doing an assignment, and I thought i should use a linked list to store some data. The problem is that the list doesn't retain all nodes. When adding finishes and I try to see the nodes, it only shows the last node that was added to list. I will write the relevant part below, I hope someone could point out what the problem is.( I suspect that it must be something related to malloc. the address gets destroyed after the functions finishes its work, but am not sure. Also I should point out, that I tested, printing data while they were being added, and it did show that they were being added properly to the list).



/**
* Adds command name and it's hash onto the linked list
* returns 1, if successful
* returns 0, if failed
*/

int addToList(struct CMDList *head, char *pathCommand[], char *hash){

int result = 0;

/** If head was pointing to NULL, list empty, add at the beginning */
if(head->path == NULL){

head->path = pathCommand[0];
head->command = pathCommand[1];
head->hash = hash;
head->next = NULL;
result = 1;

}else{

struct CMDList *current = head;

/** Find tail of the list */
while(current->next != NULL){

current = current->next;
}
current->next = (struct CMDList *)malloc(sizeof(struct CMDList));
if(current->next != NULL){

current->path = pathCommand[0];
current->command = pathCommand[1];
current->hash = hash;
current->next = NULL;
result = 1;

}

}

return result;

}


MAIN Program:



int main(int argc, char *argv[]){

/** CODE DELETED */

/** initialize list for storing cmds from config file */
/** cmdList is the head node that i use to traverse the list */
cmdList = (struct CMDList *)malloc(sizeof(struct CMDList));
if(cmdList != NULL){

cmdList->path = NULL;
cmdList->command = NULL;
cmdList->hash = NULL;
cmdList->next = NULL;
}else{

printError("Silent Exit: couldn't initialize list to store commands of config file");
exit(1);
}


/** CODE DELETED **/

/** add new data to the list */
if(!addToList(cmdList,arrayCommand,sha)){

printError("Silent Exit: couldn't add to list");
exit(1);
}

}



Segfaul out from debugger



I have a big problem with this program that simulates a database, everytime that i call the Database_set function, it return segfaul, but when i use gdb for debugging, everythings runs fine.


With more test, i found that everything work well during debugging if i create a new database (a file used for store datas) without reusing the already created databases, if i do things in this way, the call to Database_set won't return segfaul.


Out from debugger, this trick doesn't work and i get segfaul every time i try to access at line 122 addr->set, even if addr isn't a NULL pointer, because the previous call to malloc doesn't get error.


Here is the code :



#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

struct Address {
int id;
int set;
char *name;
char *email;
};

struct Database {
int MAX_DATA;
int MAX_ROWS;
struct Address *rows;
};

struct Connection {
FILE *file;
struct Database *db;
};

void die(const char *message)
{
if(errno) {
perror(message);
} else {
printf("ERROR: %s\n", message);
}

exit(1);
}

void Address_print(struct Address *addr)
{
printf("%d %s %s\n",
addr->id, addr->name, addr->email);
}


void Database_load(struct Connection *conn)
{
int rc = fread(conn->db, sizeof(struct Database), 1, conn->file);
if(rc != 1) die("Failed to load database.");
}


struct Connection *Database_open(const char *filename, char mode)
{
struct Connection *conn = malloc(sizeof(struct Connection));
if(!conn) die("Memory error");

conn->db = malloc(sizeof(struct Database));
if(!conn->db) die("Memory error");

if(mode == 'c') {
conn->file = fopen(filename, "w");
} else {
conn->file = fopen(filename, "r+");

if(conn->file) {
Database_load(conn);
}
}

if(!conn->file) die("Failed to open the file");

return conn;
}

void Database_close(struct Connection *conn)
{
if(conn) {
if(conn->file) fclose(conn->file);
if(conn->db) free(conn->db);
free(conn);
}
}

void Database_write(struct Connection *conn)
{
rewind(conn->file);

int rc = fwrite(conn->db, sizeof(struct Database), 1, conn->file);
if(rc != 1) die("Failed to write database.");

rc =fflush(conn->file);
if(rc == -1) die("Cannot flush database.");
}

void Database_create(struct Connection *conn)
{
printf("Please, insert max database rows limit .....");
scanf("%d",&conn->db->MAX_ROWS);

int i = 0;

conn->db->rows = malloc(sizeof(struct Address)*conn->db->MAX_ROWS);
if (!conn->db->rows) die("Memory error !");

for (i = 0; i < conn->db->MAX_ROWS; i++) {

/* struct Address addr = {.id = i, .set = 0};
conn->db->rows[i] = addr; */

conn->db->rows[i].id = 1;
conn->db->rows[i].set = 0;
}
}

void Database_set(struct Connection *conn, int id, const char *name, const char *email)
{

printf("Please, insert max data limit ....");
scanf("%d", &conn->db->MAX_DATA);


struct Address *addr = &conn->db->rows[id];

if(addr->set) die("Already set, delete it first");

addr->set = 1;

addr->name = malloc(conn->db->MAX_DATA);
if(!addr->name) die("Memory error !");

char *res = strcpy(addr->name, name);
if(!res) die("Name copy failed");


addr->email =malloc(conn->db->MAX_DATA);
if(!addr->email) die("Memory error !");

res = strcpy(addr->email, email);
if(!res) die("Email copy failed");


}

void Database_get(struct Connection *conn, int id)
{
struct Address *addr = &conn->db->rows[id];

if(addr->set) {
Address_print(addr);
} else {
die("ID is not set");
}
}

void Database_delete(struct Connection *conn, int id)
{
conn->db->rows[id].id = id;
conn->db->rows[id].set = 0;
}

void Database_list(struct Connection *conn)
{
int i = 0;
struct Database *db = conn->db;

for(i = 0; i < conn->db->MAX_ROWS; i++) {
struct Address *cur = &db->rows[i];

if(cur->set) {
Address_print(cur);
}
}
}

int main(int argc, char *argv[])
{

if(argc < 3) die("USAGE: ex17 <dbfile> <action> [action params]");

char *filename = argv[1];
char action = argv[2][0];

struct Connection *conn = Database_open(filename, action);

int id = 0;

if (action != 'c')
{
if (argc > 3) id = atoi(argv[4]);
if (id >= conn->db->MAX_ROWS) die("There's not that many records.");
}

switch(action) {
case 'c':
Database_create(conn);
Database_write(conn);
break;

case 'g':
if(argc != 4) die("Need an id to get");
Database_get(conn, id);
break;

case 's':
if(argc != 6) die("Need id, name, email to set");

Database_set(conn, id, argv[4], argv[5]);
Database_write(conn);
break;

case 'd':
if(argc != 4) die("Need id to delete");

Database_delete(conn, id);
Database_write(conn);
break;

case 'l':
Database_list(conn);
break;
default:
die("Invalid action, only: c=create, g=get, s=set, d=del, l=list");
}

Database_close(conn);

return 0;
}



RtlCopyMemory PUNICODE_STRING to WCHAR segfaults



I am essentially converting PUNICODE_STRING to constant size WCHAR[] in my kernel driver, trying to avoid overflow. My approach works 99% of the time, but sometimes I get segmentation fault from the first RtlCopyMemory, most useful output from the debugger is something like:



PAGE_FAULT_IN_NONPAGED_AREA (50)
Invalid system memory was referenced. This cannot be protected by try-except,
it must be protected by a Probe. Typically the address is just plain bad or it
is pointing at freed memory.
Arguments:
Arg1: ffffc0016c0dd000, memory referenced.
Arg2: 0000000000000000, value 0 = read operation, 1 = write operation.
Arg3: fffff800adea85bd, If non-zero, the instruction address which referenced the bad memory
address.
Arg4: 0000000000000000, (reserved)


What is wrong with my approach (see below for example)?



typedef struct _MYRESULT {
WCHAR Result[512];
} MYRESULT;

void myFunction(
_Inout_ MYRESULT *result,
_In_ PUNICODE_STRING s
)
{
if (s->Length < 511) {
// It is usually this RtlCopyMemory that crashes the kernel
RtlCopyMemory(result->Result, s->Buffer, sizeof(WCHAR)*s->Length);
// NULL terminate
result->Result[(sizeof)WCHAR)*s->Length)] = 0;
} else {
RtlCopyMemory(result->Result, s->Buffer, sizeof(WCHAR)*512);
// NULL terminate
result->Result[511] = 0;
}
}



How to use MPI to open MSN which on another computer,?



i am learning MPI,i want to relize like this: how i can start msn which on another computer by C Programming with MPI?




Child process cannot write to the file?




#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <errno.h>

int main() {
FILE *f = fopen("stories.txt", "w");


if (!f) {
error("Can't open stories.txt");
}

pid_t pid = fork();
if (pid == -1) {
error("Can't fork process");
}

if (!pid) {

fprintf(f, "f---- child process wrote\n");

printf("---- child process wrote\n");

if (execl("/bin/ls", "/bin/ls", NULL) == -1) {
error("Can't run script");
}

}

fprintf(stdout, "parent process wrote it after fork!\n");
fprintf(f, "parent process wrote it before return main!\n");
return 0;
}


When I run the above code in Ubuntu Linux 64-bit, this



fprintf(f, "f---- child process wrote\n");


is not written in the stories.txt file.


Can you help me explain why this happens?


When I comment out the execl then the write to the file from the child process is done OK.




error: cannot increment value of type 'char [6]'



I am trying to learn pointers and string literals in C/C++. As per my understanding, string literals are char arrays with a null \0 at the end. Also we can basically do all the pointer arithmetic operations on array like increment and decrement.


But when I am trying to run the following code:



#include <iostream>
using namespace std;

int main (){
char *c ="Hello";
char d[6];

while(*d++ = *c++);

cout<<c<<endl<<d;
}


I am getting the following error,



error: cannot increment value of type 'char [6]'
while(*d++ = *c++);


My assumption for this code was, that the values of string literal c will be copied to char array d.




file reading in c not stopping [duplicate]




This question already has an answer here:




i am trying to make a file and then read it. The file will take the batch no of student, student name and fees. it is a sequential file type. No problem in time of creating file but the problem during reading the file. in time of reading in the console it is reading only the first entry and printing it....not stopping. i am unable to caught the fault. The code has given below.



#include<stdio.h>
int main(void)
{
int batch=0;
char name[100];
float fees=0;

FILE *studentData;

if( (studentData=fopen("studentData.dat","r")) == NULL)
{
puts("Sorry, file opening is not possible.");
}
else
{
printf("%2s%5s%5s\n","Batch","Name","Fees");
fscanf(studentData,"%d%s%f",&batch, name, &fees);

while(!feof(studentData))
{
printf("%d %s %f\n",batch,name,fees);
fscanf( studentData, "%d%s%f",&batch, name, &fees);
}
}

fclose(studentData);
return 0;
}



dimanche 29 mars 2015

What is the difference between the address stored and displayed in C and C++?



In C, if I make a variable and print its address like this:



int a;
int main (void) {
printf ("%p", &a);
return 0;
}


The output was: 00AA


The same program in C++ using the line:



cout << &a << endl;


The output was: 0x8f970aa


What is the difference between these two?


I compiled both the programs using Turbo C.




Ball Game : Project



I'm working on a project where a ball will have random motion, the score displayed on top left corner and timer function of 1 min on top right corner. The purpose is that player will click on the ball and score will be incremented by one and the speed of the ball will increase. Till now I have made random motion, score displayed but I'm not able to calculate the position of the ball as in when the cursor goes over the ball then the score needs to be displayed otherwise not. So help me in detecting mouse over the moving ball. Here is my code :



#include<GL/glut.h>
#include<math.h>
#include<stdbool.h>
#include<stdio.h>
#define PI 3.14159265f


GLfloat ballRadius = 0.2;
GLfloat ballX = 0.0f;
GLfloat ballY = 0.0f;
GLfloat ballXMax,ballXMin,ballYMax,ballYMin;
GLfloat xSpeed = 0.02f;
GLfloat ySpeed = 0.007f;
int refreshMills = 30;
int x1,xa,ya;
int score = 0;
int last_mx = 0, last_my = 0, cur_mx = 0, cur_my = 0;
int arcball_on = false;
int posx = -1,posy=0,posz=1;
char *string;
GLdouble clipAreaXLeft,clipAreaXRight,clipAreaYBottom,clipA reaYTop;




void color()
{
if(score<=5)
glColor3f(1.0,0.0,0.0);
else
glColor3ub( rand()%250, rand()%250, rand()%250 );
}
void balldisp()
{
glTranslatef(ballX,ballY,0.0f);
glBegin(GL_TRIANGLE_FAN);
color();
glVertex2f(0.0f,0.0f);
int numSegments = 100;

GLfloat angle;
int i;
for(i=0;i<=numSegments;i++)
{
angle = i*2.0f*PI/numSegments;
glVertex2f(cos(angle)*ballRadius,sin(angle)*ballRa dius);
}
glEnd();

ballX += xSpeed;
ballY += ySpeed;

if(ballX > ballXMax)
{
xa=ballX;
ballX = ballXMax;
xSpeed = -xSpeed;

}
else if(ballX < ballXMin)
{
xa=ballX;
ballX = ballXMin;
xSpeed = -xSpeed;

}
if(ballY > ballYMax)
{
ya=ballY;
ballY = ballYMax;
ySpeed = -ySpeed;

}
else if(ballY < ballYMin)
{
ya=ballY;
ballY = ballYMin;
ySpeed = -ySpeed;

}
}

void scoredisp()
{
int z,j=0,k=0;
z=score;
glColor3f(1.0,0.0,0.0);
glLoadIdentity();
glRasterPos2f(-1,1 );
glutBitmapCharacter (GLUT_BITMAP_TIMES_ROMAN_24,'S');
glutBitmapCharacter (GLUT_BITMAP_TIMES_ROMAN_24,'C');
glutBitmapCharacter (GLUT_BITMAP_TIMES_ROMAN_24,'O');
glutBitmapCharacter (GLUT_BITMAP_TIMES_ROMAN_24,'R');
glutBitmapCharacter (GLUT_BITMAP_TIMES_ROMAN_24,'E');
glutBitmapCharacter (GLUT_BITMAP_TIMES_ROMAN_24,' ');
glutBitmapCharacter (GLUT_BITMAP_TIMES_ROMAN_24,':');

while(z > 9)
{
k = z % 10;
glRasterPos2f (-0.58,1);
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24,48+ k);
z /= 10;
glRasterPos2f(-0.62,1);
}
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24,48+ z);
}

void display()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
balldisp();
scoredisp();
glFlush();
}
void onMouse(int button, int state, int x, int y) /// I want help here to detect mouse over the ball
{



if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
arcball_on = true;
cur_mx = x;
cur_my = y;

}
else
{
arcball_on = false;
if(cur_mx==x && cur_my==y)
{
score=score+1;
}
printf("%d",score);
}



//return score;

// xSpeed=xSpeed+0.02;
// ySpeed=ySpeed+0.002;
}
void onMotion(int x, int y)
{
if (arcball_on)
{
cur_mx = x;
cur_my = y;
printf("%d",cur_mx);
}
}


void reshape(GLsizei width,GLsizei height)
{
if(height ==0) height = 1;
GLfloat aspect = (GLfloat)width / (GLfloat)height;
glViewport(0,0,width,height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(width >=height)
{
clipAreaXLeft = -1.0 * aspect;
clipAreaXRight = 1.0 * aspect;
clipAreaYBottom = -1.0;
clipAreaYTop = 1.0;
}
else
{
clipAreaXLeft = -1.0;
clipAreaXRight = 1.0 ;
clipAreaYBottom = -1.0 / aspect;
clipAreaYTop = 1.0/ aspect;
}
gluOrtho2D(clipAreaXLeft,clipAreaXRight,clipAreaYB ottom,clipAreaYTop+0.10);
ballXMin = clipAreaXLeft + ballRadius;
ballXMax = clipAreaXRight - ballRadius;
ballYMin = clipAreaYBottom + ballRadius;
ballYMax = clipAreaYTop - ballRadius;
}

void Timer(int value)
{
glutPostRedisplay();
glutTimerFunc(refreshMills,Timer,5);
}

int main(int argc,char* argv[])
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(100,100);
glutCreateWindow("Bouncing Ball");
glutMouseFunc(onMouse);
glutMotionFunc(onMotion);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutPostRedisplay();
glutTimerFunc(0,Timer,0);
glutMainLoop();

}



Parent not ignoring chiild process



I've got this function which is supposed to return to the calling main if amp is 1 without waiting for the child to finish. When it returns, it's supposed to show a prompt but it doesn't show anything?



int my_system(char** argv,int amp)
{
int pid=0;
int status;
if(amp)
{
signal(SIGCHLD, SIG_IGN);
}
pid = fork();
if(pid==0)
execvp(argv[0], argv);
else if(pid>0)
{
if(amp==0)
{
wait(&status);
if(status>=0)
return 0;
else
exit(EXIT_FAILURE);
}
else
{
return 0;
}
}


}




program to find the largest element in stack while implementing linked list but the data is not being accesed




#include<stdio.h>
#include<stdlib.h>
//structure//
struct node
{
int data;
struct node *link;
};
//function to push elements into stack//
void push(struct node *top_ref,int x)
{
struct node *new=(struct node *)malloc(sizeof(struct node));
new->data=x;
new->link=top_ref;
top_ref=new;
}
//function to get largest element//
int largest(struct node *top_ref)
{
int temp=0;
while(top_ref!=NULL)
{
if(temp<top_ref->data)
{
temp=top_ref->data;
}
top_ref=top_ref->link;
}
return temp;
}
//function to print the stack//
void print(struct node *top_ref)
{
while(top_ref!=NULL)
{
printf("%d->",top_ref->data);
top_ref=top_ref->link;
}
printf("\n");
}
//main function//
int main()
{
struct node *stack=(struct node *)malloc(sizeof(struct node));
stack=NULL;
push(stack,1);
push(stack,5);
push(stack,6);
push(stack,3);
print(stack);
printf("the largest no. is %d\n",largest(stack));
}


trying to find the largest no. in a stack there is a problem in line 20 ,32 top_ref->data is not being accesed top_ref is the last node of the linked list new to linked list and data structures


the output i am getting is



empty line
the largest no. is 0



How to Understand this #define in C [duplicate]




This question already has an answer here:




I'm currently reading "The C puzzle book" and I found a #define that I would like to understand how it works.



#define PRINT(int) printf(#int " = %d\n", int)


I've never seen something like #int before so I wrote a small program to try the above



#include <stdio.h>
#define PRINT(int) printf(#int " = %d\n", int)
int main()
{
PRINT(10);
}

Result: 10 = 10


How does the preprocessor interpret #int in this case and where can I read more about this?


Thanks.




pointing to element before array start in C99 [duplicate]




I have an array of integers:



int* counters = (int *) calloc(N, sizeof(int));


that must be indexed using one based indexes e.g. first element has index 1, second element has index 2, etc. Since performance was very important I decided to use a trick:



int* oneIndexedCounters = counters - 1;


that allow me to use one based indexing without subtracting 1 from indexes:



// A[i] - contains one based indexes
for (int i = 0; i < K; i++) {
oneIndexedCounters[A[i]] += B[i]; // many times in code
// some other operations on oneIndexedCounters
}


insted of:



for (int i = 0; i < K; i++) {
counters[A[i]-1] += B[i];
// ...
}


counters array is returned by my function so I couldn't allocate dummy element at array beginning.


Is pointing one element before array valid (for example when array is on memory page boundary) when you are not dereferencing that pointer? Or is there other solution that is less tricky and gives good performance?




Saving registers state in COM program



I disassembled a simple DOS .COM program and there was some code which saves and restores registers values



PUSH AX ; this is the first instruction
PUSH CX
....
POP CX
POP AX
MOV AX, 0x00 0x4C
INT 21 // call DOS interrupt 21 => END


This is very similar to function prologue and epilogue in C programs. But prologues are added automatically by compiler, and the program above was written manually in assembler, so the programmer took full responsibility for saving and restoring values in this code.


My question is what will happen if I unintentionally forgot to save some registers in my program?


And what if I intentionally replace these instructions to NOP in HEX editor? Will this lead to program crash? And why called function is responsible for saving outer context on the stack? From my point of view this should be done somehow in calling function to prevent problems if I use 3rd party libraries and poorly written code which may break my program execution.




how to use MPI_Scatterv() properly



I am having a problem using MPI_Scatterv in a parallel program. Here is how it is defined :


int MPI_Scatterv(const void *sendbuf, const int *sendcounts, const int *displs, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm)


the way I understood it , the deference between MPI_Scatterv and MPI_Scatter is the fact that in MPI_Scatterv segments do not have to be of the same length and they don't have to be continuous (gaps in memory are allowed). the part I do not understand is if the recvbuf can be an array of different size for each process then what should be used for recvcount! (lets say I want to send 5 element of sendbuf to process 0 and 15 to process 1 ! what should be the value of recvcount?)


Thank you in advance




Screen colour defaulting to normal when UAC message pops up (undetectable)



I've created a program to automatically adjust the colour filter of the screen according to sunset and sunrise. I use the GetDeviceGammaRamp() and SetDeviceGammaRamp() methods taken from here to achieve this.


However, there is a problem. When the computer wakes up from sleep, or when a UAC message pops up (e.g: from opening an installation exe file), then on my laptop, the screen colour returns to normal. All well and good if it's temporary, but the way it does this though seems non-standard, as afterwards, GetDeviceGammaRamp() returns the same previous colour, not the shown new colour! Also if I use SetDeviceGammaRamp() to try and set the old colour back again, it refuses to set. HOWEVER, if I use SetDeviceGammaRamp() to change the RGB colour just SLIGHTLY (e.g: RGB = 80,80,81 instead of the old 80,80,80), then Windows will happily set the colour to that.


If only I had a fool-proof way of detecting when Windows changes the screen's colour like this. Or failing that, if only it would respond to changing the colour back to the old colour instead of thinking "but you're already at that RGB colour, so why would you want to set it again!", when clearly it's not.


Unfortunately unless I find a solution, I have to force the program to flash to a very slightly different colour every minute or so (which many people including myself) can notice. This is in case a UAC prompt or computer wake-up happens which changes the screen's colour.


By the way, the famous F.lux program hasn't solved the problem as their program has the issue too. Interestingly, my desktop keeps the same colour when a UAC prompt comes up - it's just my laptop which has the issue.




Good C-coding style for multiple lines if conditions



I am proramming on a project and I got the problem, that i´ve got a lot of if conditions and it might get really hard for other people to read. Here is the C - Code.


I couldn´t find a similiar question on the internet yet. Do you have an idea or example how to make it more readable?



if( ((g_cycle_cnt == uartTxSecondaryMsg[3][msgPos[3]].sliceNo) || //correct slicenumber...
(uartTxSecondaryMsg[3][msgPos[3]].sliceNo == -1) || // or as fast as possible...

( (uartTxSecondaryMsg[3][msgPos[3]].sliceNo == -2) &&
((uartTxSecondaryMsg[3][msgPos[3]].timeFrameBegin>=g_uptime_cnt) &&
(uartTxSecondaryMsg[3][msgPos[3]].timeFrameEnd<=g_uptime_cnt)))) &&

((dataProcessingFlag & SECONDARY_MSG_ANNOUNCED_CH4) == SECONDARY_MSG_ANNOUNCED_CH4) )



decoding sntp client fields from a 48 byte char buffer



I am trying to create a simple network time protocol (sntp) client in c on linux. I am trying to decode the 32 and 64bit ntp fields recieved from the server. I am using a char buffer[48] to store the sntp header. So buffer[4] to 8 is root delay, buffer[8] to 12 is root dispersion etc. The fields i have mentioned have to be changed from big to little endian, and converted from ntp to unix time. I then write the final values to a sntp header struct for printing.


I have an sntp client which i have attempted, but I currently do not have a linux compiler to test the client, so would appreciate if anyone could run it and make any corrections and suggestions. I am happy to elaborate further if needed.


Thanks in advance.


sntp client:



/* talker.c - a datagram 'client'
* need to supply host name/IP and one word message,
* e.g. talker localhost hello
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> //network byte order
#include <arpa/inet.h>
#include <netdb.h>
#include <math.h>
#include <stdint.h>
#include <inttypes.h>
#include <endian.h>
//#include <byteswap.h>
/* for gethostbyname() */
//164.11.80.76
#define PORT 123
struct s_ntp {
unsigned char VN;
unsigned char LI;
unsigned char Mode;
unsigned char Stratum;
unsigned char Poll;
unsigned char Precision;
signed long root_delay;
unsigned long root_dispersion;
unsigned long reference_identifier;
int64_t reference_timestamp;
int64_t originate_timestamp;
int64_t recieve_timestamp;
int64_t transmit_timestamp;
};

//ntp structs
struct ntp_time_t {
uint32_t second;
uint32_t fraction;
};

//struct timeval {
// uint32_t sec;
// uint32_t usec;
//}

/* server port the client connects to */
int main( int argc, char * argv[]) {
int sockfd, numbytes;
//sntp struct
struct s_ntp sntpHeader;
struct hostent *he;
struct sockaddr_in their_addr;
//ntp and unix structs
struct ntp_time_t ntp;
struct timeval unix;
int address_length = 0;
//long ntp fields
int offset, delay;
unsigned long root_delay = 0, root_dis = 0, ref_iden = 0;
int64_t ref_time, ori_time, rec_time, trans_time;
//ntp buffer
unsigned char buffer[48] = {0x0};
unsigned char charSeconds[4];
unsigned char charFractions[4];
unsigned char *bytes32;
unsigned char *bytes64;
//seconds and fractions - transmit timestamp
//buffer[40] + buffer[41] + buffer[42] + buffer[43]
buffer[0] = 0x1B;

/* server address info */
if( argc != 2) {
fprintf( stderr, "usage: talker hostname\n");
exit( 1);
}
/* resolve server host name or IP address */
if( (he = gethostbyname( argv[1])) == NULL) {
perror( "Talker gethostbyname");
exit( 1);
}
if( (sockfd = socket( AF_INET, SOCK_DGRAM, 0)) == -1) {
perror( "Talker socket");
exit( 1);
}
memset( &their_addr,0, sizeof(their_addr));
/* zero struct */
their_addr.sin_family = AF_INET;
/* host byte order .. */
their_addr.sin_port = htons( PORT);
/* .. short, netwk byte order */
their_addr.sin_addr = *((struct in_addr *)he -> h_addr);
//set transmit time
gettimeofday(&unixtime, NULL);
// get time unix time via gettimeofday
gettimeofday(&unix, NUL);
unixtontp(&unix, &ntp);
//write times to buffer (transmit timestamp)
charSeconds = (unsigned char *)&ntp.second;
//fractions
charFractions = (unsigned char *)&ntp.fraction;
buffer[40] = charSeconds[1];
buffer[41] = charSeconds[2];
buffer[43] = charSeconds[3];
buffer[44] = charSeconds[4];
//seconds
buffer[45] = charFractions[1];
buffer[46] = charFractions[2];
buffer[47] = charFractions[3];
buffer[48] = charFractions[4];
if( (numbytes = sendto( sockfd, buffer, 48, 0,
(struct sockaddr *)&their_addr, sizeof( struct sockaddr))) == -1) {
perror( "Talker sendto");
exit( 1);
}
printf( "Sent %d bytes to %s\n", numbytes,
inet_ntoa( their_addr.sin_addr));
//wait for a response
address_length = sizeof (struct sockaddr);
numbytes = recvfrom(sockfd, &buffer, sizeof(buffer),
MSG_WAITALL, (struct sockaddr *)
&their_addr, &address_length);
//decode recieved sntp packet
sntpHeader.Mode = (buffer[0] & 0x04);
sntpHeader.VN = ((buffer[0] >> 3));
sntpHeader.Stratum = buffer[1];
sntpHeader.Poll = pow(2, buffer[2]);
sntpHeader.Precision = pow(2, buffer[3]);
//root delay:
//big e to little e
root_delay = ntohl((long *) concat(&buffer[4], &buffer[5], &buffer[6], &buffer[7]));
//charSeconds = ((char *) root_delay);
bytes32 = (unsigned char*)&root_delay;
ntp.second = ((long *) concat(bytes16[0], bytes[1]);
ntp.fraction = ((long *) concat(bytes16[2], bytes[3]);
ntptounix(ntp, unix);
sntpHeader.root_delay = unix.second + unix.fraction;
sntpHeader.root_delay = root_delay;
//sntpHeader.root_delay = secondsFractions32Bit(root_delay));
//root dispersion
root_dis = ntohl((long *) concat(&buffer[8], &buffer[9], &buffer[10], &buffer[11]));
bytes32 = (unsigned char*)&root_dis;
ntp.second = ((long *) concat(bytes32[0], bytes32[1]);
ntp.fraction = ((long *) concat(bytes32[2], bytes32[3]);
ntptounix(ntp, unix);
sntpHeader.root_dispersion = unix.second + unix.fraction;
//sntpHeader.root_dispersion = ntohl(root_dis);
//ref identifier
root_iden = ntohl((long *) concat(&buffer[12], &buffer[13], &buffer[14], &buffer[15]));
bytes32 = (unsigned char*)&root_dis;
ntp.second = ((long *) concat(bytes32[0], bytes32[1]);
ntp.fraction = ((long *) concat(bytes32[2], bytes32[3]);
ntptounix(ntp, unix);
sntpHeader.reference_identifier = unix.second + unix.fraction;
//reference time stamp
ref_time = htole64((uint64_t *) concat(&buffer[16], &buffer[17], &buffer[18], &buffer[19],
&buffer[20], &buffer[21], &buffer[22], &buffer[23]));
bytes64 = (unsigned char*)&ref_time;
ntp.second = ((long *) concat(bytes32[0], bytes32[1], bytes32[2], bytes32[3]);
ntp.fraction = ((long *) concat(bytes32[4], bytes32[5], bytes32[6], bytes32[7]);
ntptounix(ntp, unix);
sntpHeader.reference_timestamp = unix.second + unix.fraction;
//originate time stamp
ori_time = htole64((uint64_t *) concat(&buffer[24], &buffer[25], &buffer[26], &buffer[27],
&buffer[28], &buffer[29], &buffer[30], &buffer[31]));
bytes64 = (unsigned char*)&ori_time;
ntp.second = ((long *) concat(bytes32[0], bytes32[1], bytes32[2], bytes32[3]);
ntp.fraction = ((long *) concat(bytes32[4], bytes32[5], bytes32[6], bytes32[7]);
ntptounix(ntp, unix);
sntpHeader.reference_timestamp = unix.second + unix.fraction;
//recieve timestamp
rec_time = htole64((uint64_t *) concat(&buffer[32], &buffer[33], &buffer[34], &buffer[35],
&buffer[36], &buffer[37], &buffer[38], &buffer[39]));
bytes64 = (unsigned char*)&rec_time;
ntp.second = ((long *) concat(bytes32[0], bytes32[1], bytes32[2], bytes32[3]);
ntp.fraction = ((long *) concat(bytes32[4], bytes32[5], bytes32[6], bytes32[7]);
ntptounix(ntp, unix);
sntpHeader.reference_timestamp = unix.second + unix.fraction;
//transmit timestamp
trans_time = htole64((uint64_t *) concat(&buffer[40], &buffer[41], &buffer[42], &buffer[43],
&buffer[44], &buffer[45], &buffer[46], &buffer[47]));
bytes64 = (unsigned char*)&trans_time;
ntp.second = ((long *) concat(bytes32[0], bytes32[1], bytes32[2], bytes32[3]);
ntp.fraction = ((long *) concat(bytes32[4], bytes32[5], bytes32[6], bytes32[7]);
ntptounix(ntp, unix);
sntpHeader.reference_timestamp = unix.second + unix.fraction;
//offset and delay
offset = ((ori_time - ref_time) + (rec_time - trans_time)) / 2;
delay = (trans_time - ref_time) - (rec_time - trans_time);
//print sntp packet
printf("\nMode: %d" ,sntpHeader.Mode);
printf("\nVN : %d", sntpHeader.VN);
printf("\nStratum: %d\n", sntpHeader.Stratum);
printf("Poll: %d\n", sntpHeader.Poll);
printf("Precision: %d\n", sntpHeader.Precision);
printf("Root delay: %f\n", sntpHeader.root_delay);
printf("Root dispersion: %f\n", sntpHeader.root_dispersion);
printf("Root identifier: %f\n", sntpHeader.reference_identifier);
//timestamps
printf("Reference timestamp: %d\n", sntpHeader.reference_timestamp);
printf("Originate timestamp: %d\n", sntpHeader.originate_timestamp);
printf("Recieve timestamp: %d\n", sntpHeader.recieve_timestamp);
printf("Transmit timestamp: %d\n", sntpHeader.transmit_timestamp);
printf("Offset: %d", offset);
printf("Delay: %d", delay);
//close socket
close( sockfd);
return 0;
}

time_t transmittime() {
time_t sys_time;
sys_time = time(NULL);
//fprintf(stdout, "%u\n", (unsigned)sys_time(NULL));
return sys_time;
}

void ntptounix(struct ntp_time_t *ntptime, struct ntp_time_t *unixtime)
{
unixtime->second = ntptime->second - 0x83AA7E80; // the seconds from Jan 1, 1900 to Jan 1, 1970
unixtime->fraction = (uint32_t)( (double)ntptime->fraction * 1.0e6 / (double)(1LL<<32) );
}

void unixtontp(struct ntp_time_t *unixtime, struct ntp_time_t *ntptime) {
ntptime->second = unixtime->second + 0x83AA7E80;
ntptime->fraction = (uint32_t)( (double)(unixtime->fraction+1) * (double)(1LL<<32) * 1.0e-6 );
}