mercredi 5 août 2015

how does it happened that a variable used before it's declared?


I am confused about a function dictCreate() in file dict.c of redis implementation. I am going to paste the code here:

/* Create a new hash table 
 * T = O(1)
 */
dict *dictCreate(dictType *type, void *privDataPtr) {
    dict *d = zmalloc(sizeof(*d));
    _dictInit(d, type, privDataPtr);
    return d;
}

variable d is used in zmalloc(sizeof(*d)), but theoretically it will exist when this line was executed. So my question is how it is possible to use variable d before it is declared?



via Chebli Mohamed

Is uninitialized local variable the fastest random number generator?


I know the uninitialized local variable is undefined behaviour(UB), and also the value may have trap representations which may affect further operation, but sometimes I want to use the random number only for visual representation and will not further use them in other part of program, for example, set something with random color in a visual effect, for example:

void updateEffect(){
    for(int i=0;i<1000;i++){
        int r;
        int g;
        int b;
        star[i].setColor(r%255,g%255,b%255);
        bool isVisible;
        star[i].setVisible(isVisible);
    }
}

is it that faster than

void updateEffect(){
    for(int i=0;i<1000;i++){
        star[i].setColor(rand()%255,rand()%255,rand()%255);
        star[i].setVisible(rand()%2==0?true:false);
    }
}

and also faster than other random number generator?



via Chebli Mohamed

How to represent time in structure using C? [on hold]


I am beginning to code in C and the first assignment I got has this question of structure that I am unable to understand.Even a simple logic would be of great help.How should I proceed?

"Define a structure to represent time in hours (0-23), minutes (0-59), and seconds (0-59), and then write a function that accepts an argument of type time represented by this structure and updates it by one second & 30 seconds."



via Chebli Mohamed

GLCM in Digital image processing


I am not understanding GLCM, How to get GLCM matrix , Can anyone post the C/C++ code for getting GLCM matrix. am working with opencv.



via Chebli Mohamed

Parsing JSON array in C


I have the following JSON returned from the server, and I'm trying to access to the Values (timestamp/data):

{
   "queries": [
     {
       "sample_size": 1,
       "results": [
         {
           "name": "data",
           "group_by": [
             {
               "name": "type",
               "type": "number"
             }
           ],
           "tags": {
             "hostname": [
               "host"
             ]
           },
           "values": [
             [
               1438775895302,
               143
             ]
           ]
         }
       ]
     }
   ]
 }

I am using json-c, and am using slightly modified version of the complete json parser. However I keep getting a segmentation fault (core dumped) when attempting to access the values section using json_parse_array.

How would I go about accessing the values section?



via Chebli Mohamed

Bubble sort concept


I just want the explanation about the condition in nested for loop. How its processing, i am bit confused. I want the logic behind the conditions of two for loops.

 #include<stdio.h>
void bubblesort(int a[25],int n);

int main()
{
    int a[25],size,i;
    printf("Enter the size of an array");
    scanf("%d",&size);
    for(i=0;i<size;i++)
    {
        scanf("%d",&a[i]);
    }
    bubblesort(a,size);
    for(i=0;i<size;i++)
    {
        printf("%d\t",a[i]);
    }

    return 0;
}

void bubblesort(int a[], int n)
{

    int temp,i,j;
    for(i=0;i<n;i++)
    {
        for(j=0;j<(n-i)-1;j++)
        {
            if(a[j]>a[j+1])
            {
                temp=a[j];
                a[j]=a[j+1];
                a[j+1]= temp;
            }
        }
    }
}



via Chebli Mohamed

How to convert double value to uint8_t string[] to print on terminal window in atmel studio


I am trying to convert some double values to uint8_t String[] (in C) when programming in Atmel Studio 6.2 in order to use it further in function: usart_write_buffer_job.

And this is the whole command I am going to use further, but instead of characters, I would like to print the given double values on the screen:

   uint8_t string[] = "Hello World!\n";
   usart_write_buffer_job(&usart_instance, string, sizeof(string));

I have tried casting, but it does not work properly in Atmel, as it does not recognize the (uint8_t*)(&MyDoubleValue)



via Chebli Mohamed

String splitting examples that don't use malloc or realloc?


I was wondering if any of you out there have ever come across any examples that split large "strings" by delimiter (like a newline for example) into an array without using malloc or realloc?



via Chebli Mohamed

GMP: Are self-assignments forbidden?


I'm using the GMP library for arbitrary precision in C. All usage examples that I've seen seem to avoid self assignments such as:

Syntax : void mpz_add (mpz_t rop, const mpz_t op1, const mpz_t op2)

mpz_add(a, a, b); // Assign a+b to a

Is this usage allowed or should I only resort to assigning to a third variable?



via Chebli Mohamed

Packets incapsulation for own simple VPN


I want to do my own very simple implementation of VPN in C on Linux. For that purpose I'm going to capture IP packets, modify them and send forward. The modification consists of encryption, authentication and other stuff like in IPSec. My question is should I process somehow the size of packets or this will be handled automatically? I know it's maximum size is 65535 - 20 (for header) but accoring to MTU it is lesser. I think its because encrypted payload "incapsulated into UDP" for NAT-T is much bigger then just "normal payload" of the IP packet.



via Chebli Mohamed

cmake and 2 libraries


I have a library in my project that I would like to compile once in 32 bits and than on 64 bits (at the same time, e.g. at the end of my compilation I would like to have the 2 versions). Is that possible or I have to call 2 times cmake + make but with different parameters?



via Chebli Mohamed

How is a text area created in a programming language [on hold]


How is a textarea designed or made at a very basic level.

Let's for example say JTextArea or JEditorPane (I know only Java and Javascript). How are they made from the very basic level. Looking at the source code of the mentioned components is very hallucinating. I wish to know the basic thought process or major steps involved in creating a textArea using a programming language.

Just guessing if it involves usage of 2d graphics to show the rectangle, the border, the scrollbar and showing the text over the rectangle, etc. The reason I am thinking that way is because, some text editors have indentation guidelines, collapsible areas, etc.

Can anyone please throw some light on this question as to how can I build my own text area. I can't think of any simpler way of putting this.

Kindly refrain from mentioning different plugins. I know there are many. But I want to know the approach to create one from scratch.



via Chebli Mohamed

Color measurement and certification


I wanna obtain the LAB values using icc profile But i just know the CMYK values.

I just own two things 1) CMYK values 2) an icc profile(colorspace:CMYK, PCS:LAB) file.

Is it possible to obtain the LAB values using an icc profile? CMYK -> icc profile -> LAB (Is it a correct concept about color transfer?)



via Chebli Mohamed

Program terminated with signal 6, Aborted. Why?


I am writing a C program which crashes every time I try to stop the daemon, works well otherwise. This tells me it probably has to do something with free(). I spent sometime on debugging but still no luck. Here's the core dump

Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Core was generated by `/usr/lib/quagga/bgpd --daemon -A 127.0.0.1'.
Program terminated with signal 6, Aborted.
#0  0x00007f5e896b2165 in raise () from /lib/x86_64-linux-gnu/libc.so.6
(gdb) bt
#0  0x00007f5e896b2165 in raise () from /lib/x86_64-linux-gnu/libc.so.6
#1  0x00007f5e896b53e0 in abort () from /lib/x86_64-linux-gnu/libc.so.6
#2  0x00007f5e8a721cea in core_handler (signo=<optimized out>, siginfo=<optimized out>, context=<optimized out>) at sigevent.c:216
#3  <signal handler called>
#4  0x00007f5e896fa939 in free () from /lib/x86_64-linux-gnu/libc.so.6
#5  0x00007f5e8a70f00b in zfree (type=<optimized out>, ptr=<optimized out>) at memory.c:132
#6  0x00007f5e8abf89f6 in bgp_bfd_peer_free (peer=0x7f5e8b32ab30) at bgp_bfd.c:69
#7  0x00007f5e8abaa803 in peer_group_delete (group=group@entry=0x7f5e8b1d0dc0) at bgpd.c:2176
#8  0x00007f5e8abaa96b in bgp_delete (bgp=0x7f5e8b31af20) at bgpd.c:2730
#9  0x00007f5e8aba47bb in bgp_exit (status=<optimized out>) at bgp_main.c:238
#10 sigint () at bgp_main.c:206
#11 0x00007f5e8a721d27 in quagga_sigevent_process () at sigevent.c:111
#12 0x00007f5e8a70d7fe in thread_fetch (m=0x7f5e8b1c8900, fetch=fetch@entry=0x7fff76f2f3d8) at thread.c:1279
#13 0x00007f5e8aba4592 in main (argc=4, argv=0x7fff76f2f598) at bgp_main.c:452

Anyone have idea what is signal 6 and why is it being generated?



via Chebli Mohamed

Loading .dll with ctypes


I have a .dll with dependencies to some other (Sundials ODE solver) .dlls. I use windows 8.1 with mingw to compile and link the c-code I use for my .dll. When trying to load them with Python and ctypes I get a pop-up with a System error: cannot find libsundials_cvode.dll since it does not exist on the computer and when you close the popup Python spits out WindowsError: [Error 126] Cannot find the module Cannot understand why this is, because gcc compiles and links the files fine without errors (and yes, they do exist)... I have even tried to copy the dependent dlls into the directory where my python script is, without success.

I run the following compile and linker commands without any warnings or errors

gcc -c -I c:\sundials\include cfile.c
gcc -shared -o clib.dll cfile.o -L. C:\sundials\instdir\lib\libsundials_cvode.dll -L. C:\sundials\instdir\lib\libsundials_nserial.dll

My python test script giving the abovementioned error is

import ctypes
lib = ctypes.cdll.LoadLibrary('clib.dll')

I'm a beginner with gcc and c, but quite experienced with Python. Any suggestions what might be the reason?



via Chebli Mohamed

How to create a dynamic array of strings with the space just necessary for each string in C


I want to have an array of pointers to strings,and just get the space necessary for each string. I know malloc and getc are required but not familiar with the use of them.

Here is part of my code. It gives the error message "Segmentation fault" ....

char **allstrs;
char *one_str;
int totstrs=0,current_size= INITIALSIZE;

allstrs = (char **)malloc(current_size*sizeof(char*)); //dynamic array of strings
while(getstr(one_str)!=EOF){
    if(totstrs == current_size){
        current_size *=2;
        allstrs = realloc(allstrs, current_size*sizeof(char*));
    }
    strcpy(allstrs[totstrs],one_str);
    printf("String[%d] is : %s\n",totstrs,allstrs[totstrs]);
    totstrs ++;

}
free(allstrs);   //deallocate the segment of memory

return 0;

and the function getstr called

char c; 
int totchars=0, current_size=INITIALCHARS;

str = (char*)malloc(sizeof(char));
while(c!='\n'){
    c = getc(stdin);     
    if(c==EOF){
        return EOF;
    }

    if(totchars == current_size){
        current_size *=2;
            str = (char*)realloc(str,current_size*sizeof(char));
    }
        str[totchars] = c;  //store the newly-read character    
    totchars++;
}
str[totchars]='\0';   //at the end append null character to mark end of string

return 0;

}



via Chebli Mohamed

How to send CTRL+C WITH JSCH?


I'm using jsch ChannelShell to send commands to a remote system, but I can't send special commands like ctrl+c. I tried many things, but have no success.

Any help would be appreciated.



via Chebli Mohamed

What alterations must I do to this code.. I am receiving a Wrong answer message


All submissions for this problem are available.

Pooja would like to withdraw X $US from an ATM. The cash machine will only accept the transaction if X is a multiple of 5, and Pooja's account balance has enough cash to perform the withdrawal transaction (including bank charges). For each successful withdrawal the bank charges 0.50 $US. Calculate Pooja's account balance after an attempted transaction. Input

Positive integer 0 < X <= 2000 - the amount of cash which Pooja wishes to withdraw. Nonnegative number 0<= Y <= 2000 with two digits of precision - Pooja's initial account balance. Output

Output the account balance after the attempted transaction, given as a number with two digits of precision. If there is not enough money in the account to complete the transaction, output the current bank balance.

  • Example - Successful Transaction

Input: 30 120.00

Output: 89.50

  • Example - Incorrect Withdrawal Amount (not multiple of 5)

Input: 42 120.00

Output: 120.00

  • Example - Insufficient Funds

Input: 300 120.00

Output: 120.00

**

  • In reference to the above problem... I am receiving a wrong output message on submission! Can somebody help me out? I believe i have covered all cases! But guys, do take a look

**

#include<stdio.h>
#define bank_charge 0.5
int main()
{
    float X, Y,new_balance;
    X=0, Y = 0;

    printf("With amt and balance ");
    scanf("%f%f", &X, &Y);
    if (X > 0 && X <= 2000 && Y >= 0 && Y <= 2000)
    {
        if (X > Y || ((Y-0.5-X)<0))
        {   printf("Insufficient Funds\n");
            printf("%0.2f", Y);
            return 0;

        }
        if ((int)X % 5 == 0)
        {
            new_balance = (Y - X) - bank_charge;
            printf("%0.2f", new_balance);
            return 0;

        }
        printf("%0.2f", Y);
            }
    return 0;
}



via Chebli Mohamed

calculate difference between cells in an array [on hold]


I want to calculate the difference between every cell in one primary row to other rows and then sum the diff.

Primary row: - [11,19,59,69,9]

other row:   - [10,20,30,20,50]
diff         - [|11-10|,|19-20|,|59-30|,|69-20|,|9-50|] = [1,1,29,49,41] 
sum(diff)    = 1 + 1 + 29 + 49 + 41 = 121

How can i do it ?



via Chebli Mohamed

how can source files see other files without path in a cmake project?


In a CMAKE project I have created 2 folders, a and b, each of which has include and src directories:

-- MyProject

CMakeLists.txt

---- a

------ include

-------- a.h

---- b

------ include

-------- b.h

...

a.h includes b.h. But only if the path is specified, ie, #include "../../b/include/b.h".

How can I configure cmake so that all project files can see each other without specifying the path? eg: #include "b.h"



via Chebli Mohamed

Could anyone explain the below code snippet?


void dec_exp(Decimal *result, const Decimal *a, unsigned int b)
    {
        Decimal tmp, power = *a;
        dec_parse(result, "1");
        while (b)
        {
            if (b & 1)
            {
                tmp = *result;
                dec_mul(result, &tmp, &power);
            }
            if (b >>= 1)
            {
                tmp = power;
                dec_mul(&power, &tmp, &tmp);
            }
    }
}

Where Decimal is a structure variable containing a decimal value, it's length and the position where the decimal point exists.

Passed arguments in the function: a is the base value and b is power. And result will store the value a^b after computation.

dec_parse(Decimal &x,string y) will do a parsing of y into decimal and extract info like the postion of decimal point, trim leading and trailing zeros and converts string into a Decimal structure variable.

dec_mul(Decimal result, Decimal &x, Decimal &y) will multiply x and y and store the value after multiplication in result.

I just want to know how two "if conditions" work in the while loop and when does the while loop get terminated and the time complexity of the snippet.



via Chebli Mohamed

calculate lowesr differents between 5 cells to other 5 cells [on hold]


I have this row - [11,19,59,69,9] lets call it FIRST . and i have another ~ 100Million rows with the same format . [10,20,30,20,50], [15,50,60,70,10] ... ... I need to compare each number from FIRST row to each number in the corresponding cell in each row from the 100M rows , and take the abs diff between those two values and sum all of the diff. Example :

FIRST - [11,19,59,69,9]
row   - [10,20,30,20,50]
diff  - [|11-10|,|19-20|,|59-30|,|69-20|,|9-50|]  = [1,1,29,49,41] 
sum(diff) = 1+1+29+49+41 =121

And i need to do this comparison between the FIRST and the rest of the rows and output the row with the smallest diff.

What is the best way to do it ? 
I need to implement it on my SQL DATABASE .
Maybe there is SQL query for this ? or maybe i should develop some inner function via c, or c++ ? 

Thanks !



via Chebli Mohamed

How to get all the native methods that have been called with gdb?


I have a program I want to debug. I would like to get all native methods that are called without setting any breakpoints, since the program I run exhibit a weird behavior and skip compiling the methods it is supposed to do.

Is there a way to have all native methods that have been called by a java program with gdb (without setting breakpoints) ?



via Chebli Mohamed

Can anyone provide some example of aerospike database usage in a C/C++ program? [on hold]


I want something easy to understand, because their community and examples got me confused.



via Chebli Mohamed

Undefine macro defined twice


I want to use a macro defined in different header files with the same name and different implementations. I have two header files h1.h and h2.h. In the first header file I defined:

#define PRINT  printf(" hi , macro 1\n"); 

and in the second header file

#define PRINT  printf(" hi , macro 2\n");

in main() when I try to use PRINT it is printed depending on the order of inclusion. I found some similar problems and they used a wrapper, by including the first header file then defining an inline method:

inline void print1() {
      PRINT();
}

and then undefining PRINT and including the second header file. In main() when I call print1() and PRINT I got the output from them both. My missing point is how after we have undefined the PRINT from the first header file we are still able to have it - in other words what happens when we call it inside the inline function? Did the compiler copy the value of PRINT and assign it to the function and save the function in some way?



via Chebli Mohamed

Reading TCP_NODELAY using getsockopt returning a weird value


I am trying to verifying that my setting of TCP_NODELAY is working by reading it back after I set it.

Im setting the value to '1', but when I read it back, its set to '4'. Im afraid im doing something wrong.

Heres my code:

    int tcpBefore;
    socklen_t tcpBeforeLen = sizeof(tcpBefore);
    int res = getsockopt(socket, IPPROTO_TCP, TCP_NODELAY, &tcpBefore, &tcpBeforeLen);

    // Turn on TCP no delay
    int tcpNoDelay = 1;
    res = setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, (void *)&tcpNoDelay, sizeof(tcpNoDelay));

    int tcpAfter;
    socklen_t tcpAfterLen = sizeof(tcpAfter);
    res = getsockopt(socket, IPPROTO_TCP, TCP_NODELAY, &tcpAfter, &tcpAfterLen);

The value I get for 'tcpBefore' is '0'. The value I get after I set it is '4'. This seems odd.

Is there something I am doing wrong?



via Chebli Mohamed

MPI_Init must be called by one thread only


The ref of MPI_Init, states:

This routine must be called by one thread only. That thread is called the main thread and must be the thread that calls MPI_Finalize.

How to do this? I mean every example I have seen looks like this and in my code, I tried:

MPI_Comm_rank(MPI_COMM_WORLD, &mpirank);
bool mpiroot = (mpirank == 0);
if(mpiroot)
  MPI_Init(&argc, &argv);

but I got:

Attempting to use an MPI routine before initializing MPICH

However, notice that this will work fine, if I leave it as in the example, I just had to re-check, because of my code's failure here.


I am thinking that because we call mpiexec -n 4 ./test, 4 processes will be spawned, thus all of them will call MPI_Init. I just printed stuff at the very first line of main() and they will be printed as many times as the number of processes.



via Chebli Mohamed

How can I compile and run this project?


http://ift.tt/1N9U7qQ

i want to learn how to create a more efficient malloc and I found this project. I can run make to compile it:

$ make tstmalloc
make: `tstmalloc' is up to date.

But how can I run and test it? I read the readme file but it is not detailed enough. I want to compile all the programs, test all the programs and understand what the programs do. But if I run just make then it complains in a manner that I don't understand:

$ make
gcc  -g -Wall -ansi -DSTRATEGY=2   -c -o malloc.o malloc.c
malloc.c: In function ‘morecore’:
malloc.c:77:3: warning: implicit declaration of function ‘getpagesize’ [-Wimplicit-function-declaration]
   noPages = ((nu*sizeof(Header))-1)/getpagesize() + 1;
   ^
malloc.c:78:84: error: ‘MAP_ANONYMOUS’ undeclared (first use in this function)
   cp = mmap(__endHeap, noPages*getpagesize(), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
                                                                                    ^
malloc.c:78:84: note: each undeclared identifier is reported only once for each function it appears in
malloc.c:85:5: warning: implicit declaration of function ‘perror’ [-Wimplicit-function-declaration]
     perror("failed to get more memory");
     ^
make: *** [malloc.o] Error 1

And if I try to compile the programs individually I get another error msg that I don't understand:

$ gcc malloc.c 
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 11



via Chebli Mohamed

i cant interpret can anyone tell what it says [on hold]


/*Implement List ADT(Abstract Data Type) with main ADT functions like insert(),  delete(), search(), traverse().  Use Structure or Class for defining the ADT.  Use Static Array as a Data Member it can be of any type  (Primitive or User-defined). Declare necessary parameters and return types for the functions. */



via Chebli Mohamed

how to fix error c2065 in VS2003


I was compiling and encountered my 1 and only error.

error c2065: 'AhnHS_Callback' : undeclared identifier

Anyone can help me with this? I tried possible solutions, but still no luck for this. Hope someone can help me

int antihackNotFound = 0;
TCHAR    *pEnd = NULL;
TCHAR    szFullFileName[MAX_PATH] = { 0, };
TCHAR    szMsg[255];
int        nRet;
GetModuleFileName(NULL, szFullFileName, MAX_PATH);
pEnd = _tcsrchr( szFullFileName, _T('\\')) + 1;
if (!pEnd)
{
    return FALSE;    
}
*pEnd = _T('\0');
_stprintf(g_szIniPath, _T("%s"), szFullFileName);                
_stprintf(g_szHShieldPath, _T("%s\\HackShield"), szFullFileName);
_tcscat(szFullFileName, _T("HackShield\\EhSvc.dll"));            
_tcscat(g_szIniPath, _T("MiniAEnv.INI"));        
nRet = _AhnHS_Initialize(szFullFileName, AhnHS_Callback, 
    1000, "B228F2916A48AC24", AHNHS_CHKOPT_ALL|AHNHS_SELFDESTRUCTION_RATIO_FAST|
AHNHS_DISPLAY_HACKSHIELD_TRAYICON|AHNHS_CHKOPT_STANDALONE|
AHNHS_CHKOPT_LOADLIBRARY|AHNHS_CHKOPT_LOCAL_MEMORY_PROTECTION,
    AHNHS_SPEEDHACK_SENSING_RATIO_GAME);
if (nRet != HS_ERR_OK)
{
    _stprintf(szMsg, _T("HackShield Initialize Error. (Error Code = %x)."), nRet);
    MessageBox(szMsg, "GameSama.com", MB_OK);
    return FALSE;
}
nRet = _AhnHS_StartService();
assert(nRet != HS_ERR_NOT_INITIALIZED);
assert(nRet != HS_ERR_ALREADY_SERVICE_RUNNING);
if (nRet != HS_ERR_OK)
{
        _stprintf(szMsg, _T("HackShield Start Error. (Error Code = %x)."), nRet);
    MessageBox(szMsg, "GameSama.com", MB_OK);
    return FALSE;
}}



via Chebli Mohamed

performance difference of pthreads


I am programming performance-sensitive code. I implement a simple scheduler to distribute workloads and master thread takes charge of the scheduler.

cpu_set_t cpus;
pthread_attr_t attr;
pthread_attr_init(&attr);
     for(int i_group =0; i_group<n_groups; i_group++){
        std::cout  << i_t<< "\t"<<i_group << "th group of cpu"  <<std::endl;
        for(int i =index ; i < index+group_size[i_group]; i++){
            struct timeval start, end;
            double spent_time;
            gettimeofday(&start, NULL);
            arguments[i].i_t=i_t;
            arguments[i].F_x=F_xs[i_t];
            arguments[i].F_y=F_ys[i_t];
            arguments[i].F_z=F_zs[i_t];
            CPU_ZERO(&cpus);
            CPU_SET(arguments[i].thread_id, &cpus);
            int err= pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpus);
            if(err!=0){
                std::cout << err <<std::endl;
                exit(-1);
            }
            arguments[i].i_t=i_t;
            pthread_create( &threads[i], &attr, &cpu_work, &arguments[i]);
            gettimeofday(&end, NULL);
            spent_time = ((end.tv_sec  - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6;
            std::cout <<"create: " << spent_time << "s " << std::endl;
        }
        i_t++;
        cpu_count++;
        arr_finish[i_group]=false;
    }
} 

like above the master thread create. For the simple explanation, i will assume i_group=1. The child threads divide and conquer a bunch of matrix-matrix multiplications. Here rank means thread_id.

int local_first = size[2]*( rank -1 )/n_compute_thread ;
int local_end = size[2] * rank/n_compute_thread-1;
//mkl_set_num_threads_local(10); 

gettimeofday(&start, NULL);
for(int i_z=local_first; i_z<=local_end; i_z++ ){
    cblas_dgemm( CblasColMajor, CblasNoTrans, CblasNoTrans,
                size[0], size[1], size[0], 1.0,  F_x, size[0],
                rho[i_z], size[1], 0.0, T_gamma[i_z], size[1] );
}
for(int i_z=local_first; i_z<=local_end; i_z++ ){
    cblas_dgemm( CblasColMajor, CblasNoTrans, CblasNoTrans,
                 size[0], size[1], size[1], 1.0, T_gamma[i_z], size[0],
                 F_y, size[1], 0.0, T_gamma2[i_z], size[0] );
}
gettimeofday(&end, NULL);
std::cout <<i_t <<"\t"<< arg->thread_id <<"\t"<< sched_getcpu()<<  "\t" << "compute: " <<spent_time << "s" <<std::endl;

Even though workload fairly distributed, the performance of each thread vary too much. see the result below

5 65 4 4 compute: 0.270229s

5 64 1 1 compute: 0.284958s

5 65 2 2 compute: 0.741197s

5 65 3 3 compute: 0.76302s

second column shows how many matrix-matrix multiplications are done in a particular thread. last column shows consumed time. When I saw this result firstly, I thought that it related to the affinity of threads. Thus, I added several lines to control the binding of threads. However, it did not change the trends of last column.

My computer has 20 physical cores and 20 virtual core. I made only 4 child threads to test. Of course, it was tested in a Linux machine



via Chebli Mohamed

Finding Largest Twin Prime


I am trying to create a c program which prompts for user input and then, finds the largest twin prime within that number. This program then loops continuously, prompting the user for an input again and again and finding the largest twin prime until the user enters -1, after which it terminates. I wrote down the basic code, but have yet been able to make it loop continuously when using certain numbers such as 20 and 65. I cannot figure out what is wrong with my code.

I seem to be having another problem as well. For 20, the values show (15,17) instead of (17,19). Obviously the logic is wrong somewhere but I am not sure exactly where either.

This is my code:

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

int prime(int x)
{
    int i,numroot;
    numroot=sqrt(x);
    for(i=2;i<=numroot;i++)
    if(x%i==0){
        return(0);
    }
    return(1);

}

int main()
{
    double N;

    printf("This program prints out all the possible twin primes until a specific number which...\nyou can choose!");
    printf("\nA note of caution: Although this program accepts decimals, the value entered must be between 5 and 10^9,inclusive of the 2 numbers.");
    printf("\nKey in -1 to exit.");
    printf("\nEnter N value upto which twin primes ought to be calculated until: ");
    scanf("%lf",&N);

    while (N!=-1) {
      if (N<5 || N>pow(10,9)) {
          printf("\nNumber not in the valid range was inputted. \nPlease reenter the value: ");
          scanf("%lf",&N);
      }
      else {
          int n;
          n=floor(N);
              int prime(int x);
          int f,originalval;

          originalval=N;
          f=prime(n);
          while(f==0){//Calculates for largest prime number below user input
            n--;
            f=prime(n);
          }
          int smallint=n-2;
          while(prime(smallint)==1){
              n--;
              f=prime(n);
              while(f==0){
                  n--;
                  f=prime(n);
              }
              int smallint=n-2;
    }
    printf("The largest twin prime pair not above %d is (%d,%d)",originalval,smallint,n);
          printf("\nPlease re-enter the value:");
          scanf("%lf",&N);
      }
    }
    printf("\nProgram successfully terminated.");
    return 0;
}



via Chebli Mohamed

String permutation - How does this backtracking recursion work?


This function basically prints all possible permutations of a string by swapping a character with all its other characters. I understand the first two calls to swap and permute. But why is swap called for the second time? I cannot understand this piece of code. Can someone please explain me how this works?

/* Function to print permutations of string
   This function takes three parameters:
   1. String
   2. Starting index of the string
   3. Ending index of the string. */
void permute(char *a, int l, int r)
{
   int i;
   if (l == r)
     printf("%s\n", a);
   else
   {
       for (i = l; i <= r; i++)
       {
          swap((a+l), (a+i));
          permute(a, l+1, r);
          swap((a+l), (a+i)); //backtrack
       }
   }
}



via Chebli Mohamed

returning array of string from function not working as expected


I am trying to pass an array of strings to a function, make some changes to it inside this function, and pass it back to main and print it to see the changes. It is not working as expected. Please tell me where I'm going wrong.

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

//don't forget to declare this function
char** fun(char [][20]);

int main(void)
{
 char strar[10][20] = { {"abc"}, {"def"}, {"ghi"}, {""},{""} }; //make sure 10 is added
 char** ret; //no need to allocate anything for ret, ret is just a placeholder, allocation everything done in fun
 int i = 0;

 ret = fun(strar);
 for(i=0;i<4;i++)
  printf("[%s] ",ret[i]);

 printf("\n");
 return 0;
}

//don't forget function has to return char** and not int. (Remember char**, not char*)
char** fun(char strar[][20])
{
 int i = 0;
 char** ret;
 ret = malloc(sizeof(void*)); //sizeof(void*) is enough, it just has to hold an address 

 for(i=0;i<5;i++)
 {
  ret[i] = malloc(20 * sizeof(char));
  strcpy(ret[i],strar[i]);
 }

 strcpy(ret[3],"fromfun");

 return ret;
}



via Chebli Mohamed

How to assign a value to a string outside the declaration in C ? Bus error/segfault


So for the sake of training I'm trying to recode the equivalent of an strstr function, after a few try I got it right, here the code:

(I know there are simpler way to do it which I did, but this time I wanted to try by using a 3rd string to stock the occurence)

 6char *my_strstr(char *s1, char *s2)
 7{
 8  int i, j;
 9  char *tmp;
 10  i = (j = 0);
 11
 12  if (s1 != '\0' && s2 != '\0')
 13    {
 14      while (s1[i] != '\0' && s2[j] != '\0')
 15        {
 16          if (s1[i] == s2[j])
 17            {
 18              tmp[j] = s1[i];
 19              j++;
 20            }
 21          i++;
 22        }
 23        printf("tmp = %s\n", tmp);
 24    }
 25  return (tmp);
 26}
 27
 28
 29int main()
 30{
 31  char a[] = "test Point123";
 32  char b[] = "Point123";
 33  char *ret;
 34
 35  ret = my_strstr(a, b);
 36  printf("ret = %s\n",ret);
 37
 38  return (0);
 39}

I get the output I wanted:

tmp = Point123
ret = Point123

But then just to be sure I tried with a longer string, and thats where the problems started. Here the string I tried,

char a[] = "test Point123456789";
char b[] = "Point123456789";

and the output I got with it:

tmp = Point123456?"1
ret = Point123456?"1
Abort trap: 6

With longer string I get sometimes segfault, sometimes bus Error 10. On some other post I figured that the Bus error 10 sometimes replace a segfault on mac OS (on which I'm coding for the 1st time, I'm used to code on linux), I didnt find anything about the trap tho.

Anyway I figured its more a code problem that my compiler and I'd like to know why my code function on smaller string but not bigger ones, and I read that it could be how I affected value to the strings I'm using but I dont understand where I'm making an error.

So if anyone could give me a clue on what I'm doing wrong I'd greatly appreciate it :)



via Chebli Mohamed

Round of a negative decimal in C


I need to round of decimal numbers to certain precision in my C program. I am facing difficulties in these type of examples

x = -0.000000001235 

which when rounded (using %.5f) to five decimals prints -0.00000.

How should I remove the negative sign?



via Chebli Mohamed

C String while using Bison/Flex


I'm working on a bison/flex project where I am using string but I'm not able to use well methods like strlen() (same for strcmp etc.)

To better explain I wrote a new short .l and .y files:

%{
#include <string>
#include "test.tab.h"
void yyerror(char*);
extern void printVars();
int yyparse(void);
char linebuf[500];


%}

%option yylineno

blanks          [ \t\n]+
text            [^<>]+


%%

\n.*  { strncpy(linebuf, yytext+1, sizeof(linebuf)); /* save the next line */
        yyless(1);      /* give back all but the \n to rescan */
       }

{blanks}        { /* ignore */ };

"<test>"        return(START);
"</test>"       return(STOP);
"<string>"      return(BEGIN_STRING);
"</string>"     return(END_STRING);
"<num>"         return(BEGIN_NUM);
"</num>"        return(END_NUM);

{text}          { yylval.str_val=strdup(yytext);
                  return(IDENTIFIER);
                }

.               return yytext[0];

%%


void yyerror(char *s){ 
    printf("--------- ERROR ---------\n");
    printf("%d: %s at %s in this line:\n%s\n", yylineno, s, yytext, linebuf);
    }

int yywrap (void){
    printf("--------- EOF ---------\n");
    }

int main(int num_args, char** args){
    if(num_args != 2) {printf("usage: ./parser filename\n"); exit(0);}
    FILE* file = fopen(args[1],"r");
    if(file == NULL) {printf("couldn't open %s\n",args[1]); exit(0);}
    yyin = file;
    yyparse();
    fclose(file);

    printVars();
}

And

%{
#include <stdio.h>
#include <string>
#define MAX_VAR     10

using namespace std;
extern int yylex();
extern void yyerror(char*);
void printVars();

string data_str[MAX_VAR];
string data_int[MAX_VAR];
int num_data_str = 0;
int num_data_int = 0;

%}



//Symbols
%union
{
    char *str_val;
};

%token START
%token STOP
%token BEGIN_NUM
%token END_NUM
%token BEGIN_STRING
%token END_STRING

%token <str_val>    IDENTIFIER

%start MyTest

%%

MyTest:
    START Block STOP
    ;

Block:
    /* empty */
    | Block 
      BEGIN_STRING IDENTIFIER END_STRING
      { if(num_data_str<MAX_VAR){
            data_str[num_data_str]=$3;
            num_data_str++;
        }
        else printf("string: %s not saved!\n", $3); }
    | Block
      BEGIN_NUM IDENTIFIER END_NUM
      { if(num_data_int<MAX_VAR){
            data_int[num_data_int]=$3;
            num_data_int++; //saved
        }
        else printf("integer: %s not saved!\n", $3); }
    ;

%%

void printVars(){
    printf("Printing Strings:\n");
    for(int i=0;i<num_data_str;i++) printf("-- %s of length \n",data_str[i].c_str(),strlen(data_str[i]));
    printf("Printing Integers:\n");
    for(int i=0;i<num_data_int;i++) printf("-- %s \n",data_int[i].c_str());

}

As you can see I have

#include <string>
using namespace std;

In this way I have the following error while compiling:

test.tab.c: In function ‘int yyparse()’:
test.tab.c:1289:35: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
       yyerror (YY_("syntax error"));
                                   ^
test.tab.c:1433:35: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
   yyerror (YY_("memory exhausted"));
                                   ^
test.y: In function ‘void printVars()’:
test.y:66:100: error: ‘strlen’ was not declared in this scope
  for(int i=0;i<num_data_str;i++) printf("-- %s of length \n",data_str[i].c_str(),strlen(data_str[i]));



via Chebli Mohamed

Error when decode AAC with avcodec_decode_audio4()


I'm trying to decode AAC with FFmpeg native decoder and encountered an error

SSR is not implemeted. Update your FFmpeg version to newest from Git. If the      problem still occurs, it mean that your file has a feature which has not implemented.

Function avcodec_decode_audio4() return -1163346256. Is this because of FFmpeg version? I downloaded shared and dev version from [http://ift.tt/1DtB22U]. Is this up to date?

Here is the source code:

#include "stdafx.h"
#include "stdio.h"
#include "conio.h"

extern "C" 
{
#ifndef __STDC_CONSTANT_MACROS
#define __STDC_CONSTANT_MACROS
#endif
#include <libavcodec\avcodec.h>
#include <libavformat/avformat.h>
}

// compatibility with newer API
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1)
#define av_frame_alloc avcodec_alloc_frame
#define av_frame_free avcodec_free_frame
#endif

#define AUDIO_INBUF_SIZE 20480
#define AUDIO_REFILL_THRESH 4096


static void audio_decode_example(const char *outfilename, const char *filename);


int main(int argc, char *argv[]) {
    audio_decode_example("D:\\sample.pcm","D:\\sample.m4a");
    getch();
    return 0;
}


/*
 * Audio decoding.
 */
static void audio_decode_example(const char *outfilename, const char *filename)
{
    AVCodec *codec;
    AVFormatContext   *pFormatCtx = NULL;
    AVCodecContext    *pCodecCtxOrig = NULL;
    AVCodecContext * pCodecCtx= NULL;
    int len;
    FILE *f, *outfile;
    uint8_t inbuf[AUDIO_INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
    AVPacket avpkt;
    AVFrame *decoded_frame = NULL;


    av_register_all();

    av_init_packet(&avpkt);

    printf("Decode audio file %s to %s\n", filename, outfilename);

    // Open file to get format context
    if(avformat_open_input(&pFormatCtx, filename, NULL, NULL)!=0){
        printf("Couldn't open file");
        return; // Couldn't open file
    }

    // Retrieve stream information
    if(avformat_find_stream_info(pFormatCtx, NULL)<0){
        printf("Couldn't find stream information");
        return; // Couldn't find stream information
    }

    // Dump information about file onto standard error
    av_dump_format(pFormatCtx, 0, filename, 0);

    // Find the first audio stream
    int audioStream = -1;
    int i =0;
    for(i=0; i<pFormatCtx->nb_streams; i++) {
        if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
            audioStream=i;
            break;
        }
    }

    if(audioStream==-1) {
        printf("Didn't find a audio stream");
        return; // Didn't find a audio stream
    }

    // Get a pointer to the codec context for the audio stream
    pCodecCtxOrig=pFormatCtx->streams[audioStream]->codec;

    // Find the decoder for the audio stream
    codec=avcodec_find_decoder(pCodecCtxOrig->codec_id);
    if(codec==NULL) {
        fprintf(stderr, "Codec not found\n");
        return; // Codec not found
    }

    pCodecCtx = avcodec_alloc_context3(codec);
    if (!pCodecCtx) {
        fprintf(stderr, "Could not allocate audio codec context\n");
        return;
    }

    if(avcodec_copy_context(pCodecCtx, pCodecCtxOrig) != 0) {
        fprintf(stderr, "Couldn't copy codec context");
        return; // Error copying codec context
    }


    /* open it */
    if (avcodec_open2(pCodecCtx, codec, NULL) < 0) {
        fprintf(stderr, "Could not open codec\n");
        return;
    }

    f = fopen(filename, "rb");
    if (!f) {
        fprintf(stderr, "Could not open %s\n", filename);
        return;
    }
    outfile = fopen(outfilename, "wb");
    if (!outfile) {
        av_free(pCodecCtx);
        return;
    }

    /* decode until eof */
    avpkt.data = inbuf;
    avpkt.size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);

    while (avpkt.size > 0) {
        int i, ch;
        int got_frame = 0;

        if (!decoded_frame) {
            if (!(decoded_frame = av_frame_alloc())) {
                fprintf(stderr, "Could not allocate audio frame\n");
                return;
            }
        }

        len = avcodec_decode_audio4(pCodecCtx, decoded_frame, &got_frame, &avpkt);
        if (len < 0) {
            fprintf(stderr, "Error while decoding. len = %d \n",len);
            return;
        }
        if (got_frame) {
            /* if a frame has been decoded, output it */
            int data_size = av_get_bytes_per_sample(pCodecCtx->sample_fmt);
            if (data_size < 0) {
                /* This should not occur, checking just for paranoia */
                fprintf(stderr, "Failed to calculate data size\n");
                return;
            }
            for (i=0; i < decoded_frame->nb_samples; i++)
                for (ch=0; ch < pCodecCtx->channels; ch++)
                    fwrite(decoded_frame->data[ch] + data_size*i, 1, data_size, outfile);
        }
        avpkt.size -= len;
        avpkt.data += len;
        avpkt.dts =
        avpkt.pts = AV_NOPTS_VALUE;
        if (avpkt.size < AUDIO_REFILL_THRESH) {
            /* Refill the input buffer, to avoid trying to decode
             * incomplete frames. Instead of this, one could also use
             * a parser, or use a proper container format through
             * libavformat. */
            memmove(inbuf, avpkt.data, avpkt.size);
            avpkt.data = inbuf;
            len = fread(avpkt.data + avpkt.size, 1,
                        AUDIO_INBUF_SIZE - avpkt.size, f);
            if (len > 0)
                avpkt.size += len;
        }
    }

    fclose(outfile);
    fclose(f);

    avcodec_close(pCodecCtx);
    av_free(pCodecCtx);
    av_frame_free(&decoded_frame);
}

I have also read this question [How to decode AAC using avcodec_decode_audio4? to decode AAC using avcodec_decode_audio4?] but no solution is provided.



via Chebli Mohamed

Probability part of Reservoir sampling?


The following algorithm is given in wiki for solving reservoir sampling with O(n^2).

Used for solving ques like this,

You must pick a subset S’ of k numbers from S such that the probability of each element of S occurring in S’ is equal (i.e., each is selected with probability k/n). You may make only one pass over the numbers. What if n is unknown?

ReservoirSample(S[1..n], R[1..k])
// fill the reservoir array
for i = 1 to k
   R[i] := S[i]

// replace elements with gradually decreasing probability
for i = k+1 to n
  j := random(1, i)   // important: inclusive range
  if j <= k
    R[j] := S[i]

The explaination given below is as follow:

The algorithm creates a "reservoir" array of size k and populates it with the first k items of S. It then iterates through the remaining elements of S until S is exhausted. At the ith element of S, the algorithm generates a random number j between 1 and i. If j is less than or equal to k, the jth element of the reservoir array is replaced with the ith element of S. In effect, for all i, the ith element of S is chosen to be included in the reservoir with probability k/i. Similarly, at each iteration the jth element of the reservoir array is chosen to be replaced with probability 1/k * k/i, which simplifies to 1/i. It can be shown that when the algorithm has finished executing, each item in S has equal probability (i.e. k/length(S)) of being chosen for the reservoir.

  1. The part i understand is that i have 2 arrays,

    1. array s[] of size n(where n can be unknown or very large). array r[] of size k, since k elements have to be chosen(also k < n).

    Now, first we fill the first 'k' elements from array s[1..n] into array r[1..k]. This obviously fills array r[1..k] completely. then, starting from index k+1 to n then starting from i=k+1 to n, we choose a random number between 1 to i, and if j

Please can someone explain the probability part here.This part specially...

Similarly, at each iteration the jth element of the reservoir array is chosen to be replaced with probability 1/k * k/i, which simplifies to 1/i. It can be shown that when the algorithm has finished executing, each item in S has equal probability (i.e. k/length(S)) of being chosen for the reservoir. To see this, consider the following proof by induction.



via Chebli Mohamed

flushing stdout of c executable


I've got program that crashes after several printing command lines. however, I cannot see the output even though those prints already performed. this lead me to the assumption that there's a buffer that dump output after accumulating enough data, and if program crashed unexpectedly, the buffer disappear.

For debugging my crash, I'd like to set this buffer to zero and avoid performance degradation, so i can see the prints prior to the crash event.

thanks



via Chebli Mohamed

Socket is open after process, that opened it finished


After closing client socket on sever side and exit application, socket still open for some time.

I can see it via netstat

Every 0.1s: netstat -tuplna  | grep 6676    
tcp        0      0 127.0.0.1:6676          127.0.0.1:36065         TIME_WAIT   -

I use log4cxx logging and telnet appender. log4cxx use apr sockets. Socket::close() method looks like that:

void Socket::close() {
    if (socket != 0) {
        apr_status_t status = apr_socket_close(socket);
        if (status != APR_SUCCESS) {
            throw SocketException(status);
        }        
        socket = 0;
    }
}

And it's successfully processed. But after program is finished I can see opened socket via netstat, and if it starts again log4cxx unable to open 6676 port, because it is busy. I tries to modify log4cxx. Shutdown socket before close:

void Socket::close() {
    if (socket != 0) {
        apr_status_t shutdown_status = apr_socket_shutdown(socket, APR_SHUTDOWN_READWRITE);
        printf("Socket::close shutdown_status %d\n", shutdown_status);
        if (shutdown_status != APR_SUCCESS) {
            printf("Socket::close WTF %d\n", shutdown_status != APR_SUCCESS);
            throw SocketException(shutdown_status);
        }
        apr_status_t close_status = apr_socket_close(socket);
        printf("Socket::close close_status %d\n", close_status);
        if (close_status != APR_SUCCESS) {
            printf("Socket::close WTF %d\n", close_status != APR_SUCCESS);
            throw SocketException(close_status);
        }
        socket = 0;
    }
}

But it didn't helped, bug still reproduced.



via Chebli Mohamed

What is the meaning of `printf("%p")` without arguments


I of course know it used to output pointer with arguments.

I read book Writing Secure Code by Michael Howard and David LeBlanc.

One program in book demonstrates how stack overflow works by strcpy()

Note printf() without arguments.

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

void foo(const char* input)
{
    char buf[10];

    //What? No extra arguments supplied to printf?
    //It's a cheap trick to view the stack 8-)
    //We'll see this trick again when we look at format strings.
    printf("My stack looks like:\n%p\n%p\n%p\n%p\n%p\n% p\n\n");

    //Pass the user input straight to secure code public enemy #1.
    strcpy(buf, input);
    printf("%s\n", buf);

    printf("Now the stack looks like:\n%p\n%p\n%p\n%p\n%p\n%p\n\n");
}

void bar(void)
{
    printf("Augh! I've been hacked!\n");
}

int main(int argc, char* argv[])
{
    //Blatant cheating to make life easier on myself
    printf("Address of foo = %p\n", foo);
    printf("Address of bar = %p\n", bar);
    if (argc != 2) 
    {
        printf("Please supply a string as an argument!\n");
        return -1;
        } 
    foo(argv[1]);
    return 0;
}

The result is

C:\Secureco2\Chapter05>StackOverrun.exe Hello
Address of foo = 00401000
Address of bar = 00401045
My stack looks like:
00000000
00000000
7FFDF000
0012FF80 
0040108A <-- return address
00410EDE

Hello
Now the stack looks like:
6C6C6548 <-- 'l','l','e','h'
0000006F <-- 0, 0, 0, 'o'
7FFDF000
0012FF80
0040108A
00410EDE

What is the meaning of printf("%p") inside code? Why it can print the content of stack?



via Chebli Mohamed

Query total CPU usage of all instances of a process on Linux OS


I have a python server that forks itself once it receives a request. The python service has several C++ .so objects it can call into, as well as the python process itself.

My question is, in any one of these processes, I would like to be able to see how much CPU all instances of this server are currently using. So lets say I have foo.py, I want to see how much CPU all instances of foo.py are currently using. For example, foo.py(1) is using 200% cpu, foo.py(2) is using 300%, and foo.py(3) is using 50%, id like to arrive at 550%.

The only way I can think of doing this myself is getting the PID of every process and scanning through the /proc filesystem. Is there a more general way available within C/Python/POSIX for such an operation?

Thank you!



via Chebli Mohamed

How much DATA section memory is loaded along with Code section in C


I have created a shared library where I have static const data section and code section of 4 functions.

Here are the details of my static const data section,

static const u32 T0[256] = { 256 NON_ZERO value };
static const u32 T1[256] = {256  NON_ZERO value };
static const u32 T2[256] = {256  NON_ZERO value };
static const u32 T3[256] = {256  NON_ZERO value };
static const u32 T4[256] = {256  NON_ZERO value };
static const u32 T5[256] = {256  NON_ZERO value };
static const u32 T6[256] = {256  NON_ZERO value };
static const u32 T7[256] = {256  NON_ZERO value };
static const u32 T8[256] = {256  NON_ZERO value };
static const u32 T9[10] = {10 NON_ZERO value };

Different functions defined just below the static const section

int A();
int B();

// Access different index of T0 - T4 table 
void C();

void D();

As per my understanding the text/code section will contain the executable instruction whereas data section will contain initialized static data ( for simplicity in my case all are static const)

Inside C() function , different index of T0,T1,T2 and T3 are accessed in random order.

Intentionally, inside C(), I have not accessed T0[0].

However, every time I call C() function, it is loading T0[0] irrespective of whether T0[0] is accessed or not inside C() function.

My question is how much adjacent memory of data section is loaded along with code section?

I was thinking may be whole 4KB page loaded, so everytime C() function called, whole 4KB page loaded , therefore T0[0] is also loaded along with it.

but, the experimental result shows THIS CONCEPT IS NOT TRUE/CORRECT.

Let me explain it elaborately as below.

I have calculated the distance between function C() and different static const data as below

Base address of C - Base address of T0[0] = 3221 Bytes
Base address of C - Base address of T1[0] = 4345 Bytes
Base address of C - Base address of T2[0] = 5369 Bytes
Base address of C - Base address of T3[0] = 6393 Bytes

So, whenever C() is invoked , ONLY 64Bytes (i.e. T0[0] ) is loaded . T0[1], T0[2],... the part of T0 array which also belong to same 4KB page with C() NOT LOADED.

In other experiment, when I add another static const of 64Byte ( like static const int DATA=10; ) before static const u32 T0[256] = {.....}

these distances become

Base address of C - Base address of T0[0] =3385 Bytes [ =64 + Base address of C - Base address of T0[0]]
Base address of C - Base address of T1[0] = 4345+64 Bytes =4409 Bytes [=64 + Base address of C - Base address of T0[0]+1024]
Base address of C - Base address of T2[0] = 5369+64 Bytes = 5433 Bytes[=64 + Base address of C - Base address of T0[0]+2*1024]
Base address of C - Base address of T3[0] = 6393 +64 Bytes = 6457 Bytes[=64 + Base address of C - Base address of T0[0]+3*1024]

Now, although T0[0] still present in same 4KB page with C(), it is not loaded whenever C() is invoked.

Note : To calculate whether T0[0] is loaded or not , before invoking C(), I just flushed T0[0] using clflush() instruction and then after C() is invoked I have calculated access time using rdtsc().

Can you help me to explain/understand WHY T0[0] is always accessed/loaded whenever C() is invoked although it is not accessed/used inside C() ?

or any link to understand the memory layout of program and size of memory loaded during execution of program.

I am using Debian OS and gcc compiler.



via Chebli Mohamed

javascript function callback in C code using Emscripten


The task is to call a javascript function as a callback in order to show a progress of while-loop operation. E.g. JS:

var my_js_fn = function(curstate, maxstate){//int variables
console.log(curstate.toString() + " of " + maxstate.toString());
}

C pseudocode:

int smth_that_calls_my_fn(int i, int max) {
/*
the_magic to call my_js_fn()
*/
}
    int main(){
    //....
        while (i < max){
        smth_that_calls_my_fn(i,max);
        }
    //....
    return 0;
    }

How can I link smth_that_calls_my_fn and my_js_fn ?



via Chebli Mohamed

Difference between POSIX Standards


Posix COntains different standards 1003.1a,b...., 1003.2.... Sometimes it is shown as POSIX.1, POSIX.2, POSIX.4. From my understanding POSIX.1(1003.1)then why they have given differnt naming convention.

POSIX Contains different profiles pse51,52.... Right now the code, what I am compiling is like given -lpthread. How can I know which POSIX profile, I am using.

I want to use specifically use POSIX PSE51 Profile. How to compile a code specifically to PSE51



via Chebli Mohamed

Which files to read if I want to create a c progam to give an output same as given by ps ax


In which files can we find the values displayed by ps ax command: TTY,STAT,TIME,COMMAND in /proc/processId directory



via Chebli Mohamed

Filling a polygon


I created this function that draws a simple polygon with n number of vertexes:

void polygon (int n)
{
    double pI = 3.141592653589;
    double area = min(width / 2, height / 2);
    int X = 0, Y = area - 1;
    double offset = Y;
    int lastx, lasty;

    double radius = sqrt(X * X + Y * Y);
    double quadrant = atan2(Y, X);

    int i;

    for (i = 1; i <= n; i++)
    {
        lastx = X; lasty = Y;
        quadrant = quadrant + pI * 2.0 / n;

        X = round((double)radius * cos(quadrant));
        Y = round((double)radius * sin(quadrant));

        setpen((i * 255) / n, 0, 0, 0.0, 1); // r(interval) g b, a, size

        moveto(offset + lastx, offset + lasty); // Moves line offset
        lineto(offset + X, offset + Y); // Draws a line from offset
    }
}


How can I fill it with a solid color? I have no idea how can I modify my code in order to draw it filled.



via Chebli Mohamed

Residual characters printed on stdout with socket communication


In a socket TCP communication, I have a server and a client. Both can read from and write to the socket.

The code is written in C and uses Linux system calls recv and write.

recv saves the received string in:

char message_array[2000];

Another array with the same dimensions is used as source for the write process.

After both the reading and writing process the following operation is performed, to clear all the array elements:

memset(&message_array, 0, sizeof(message_array));

Moreover, a fflush is performed on stdin and stdout at every write and every read process.

The server prints on its stdout what it writes and what it receives.

If I send small messages from both the terminals ("hello", "hi") even for several times (18-20), all appears to work correctly. But if I try to send longer messages (longer than 5 characters, but shorter than 2000!), the server side has some strange behaviour: it prints the message received from the client, but then it inserts a random number of the trailing characters of the previous messages. For example I have:

CLIENT MESSAGE: hello1
SERVER MESSAGE: hello2
CLIENT MESSAGE: hello3
SERVER MESSAGE: hello4 
CLIENT MESSAGE: some other characters5
SERVER MESSAGE: hello6
CLIENT MESSAGE: a long phrase 7
ters5

After several messages, the 5 characters ters5 from a previous message appear as trailing characters after the actual message, which was just a long phrase 7. Continuing the "conversation", other unexpected newline and "old" characters appears on the stdout of the server.

The code of the read and write routine is the following:

void *connection_handler_read(void *socket_read_desc)
{
    int read_sock = *(int*)socket_read_desc;
    int read_size;
    char remote_message[MAX_STRING_LEN];

    while( (read_size = recv(read_sock, remote_message, MAX_STRING_LEN, 0)) > 0 )
    {
        printf(remote_message);
        fflush(stdout);
    }

    free(socket_read_desc);
    connection_active = 0;
    return 0;
}

void *connection_handler_write(void *socket_write_desc)
{
    int write_sock = *(int*)socket_write_desc;
    char local_message[MAX_STRING_LEN];

    while( connection_active != 0 )
    {
        scanf ("%[^\n]%*c", local_message);
        write(write_sock, local_message, strlen(local_message));
        memset(&local_message, 0, sizeof(local_message));
        fflush(stdin);
    }

    free(socket_write_desc);
    return 0;
}

These two functions are invoked in the main as threads with pthread_create after a new socket connection is succesfully created (so, after a successful accept). They obviously operate on the same socket.

My questions are:

1) Is this a software problem or a socket problem?

2) Which trick should I have followed, in addition to memset and fflush?



via Chebli Mohamed

How to convert a jpg tp yuv in C?


Even though a question of this nature sounds very similar, I am having problems in converting a jpg image to yuv in C (without using opencv).

This is what I have understood as of now, how to solve this problem :

  1. Identify the structure of file formats for jpg and yuv. i.e what each byte in the file actually contains. This is what I think jpg format looks like.
  2. With the above structure I tried to read a jpg file and tried to decipher its 18th and 19th bytes. I did type cast them to both char and int but I don`t get any meaningful values for width and height of the image.
  3. Once I have read these values, I should be able to convert them from jpg to yuv. I was looking at this resource.

  4. Appropriately, construct yuv image and write it to a (.yuv) file.

Kindly help me by pointing me to appropriate resources. I will keep updating my progress on this post. Thanks in advance.



via Chebli Mohamed