vendredi 8 mai 2015

weird behaviour when working with double pointers

I need help to understand why in this little program i cannot manipulate correctly pointers:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
          void change(char *s[][15]){
              int i=0;
              while(i<5){
                  if(s[i][0]=='B') s[i][0]='v';
                  i++;
              }
          }
    /*My code is supposed to allocate dynamically 5 arrays of 15 chars each
    (like tab[5][15])and then put a message on them and try to modify the messages.
In this particular case i'm trying to change the first letter of each string to 'V'.
    I'm doing this little experience because of another program 
    in which i have difficulties accessing double arrays*/    
    int main(){
            int i;
            char **s;
            s =malloc(5*sizeof(char*));
            for(i=0;i<5;i++){
                s[i]=malloc(15*sizeof(char));
                sprintf(s[i],"Bonjour%d",i);
            }
            change(s);
            for(i=0;i<5;i++){
                printf("%s\n",s[i]);
            }
            return 0;
    }

I was expecting :

Vonjour0
Vonjour1
Vonjour2
Vonjour3
Vonjour4

but I get :

Bonjour0
Bonjour1
Bonjour2
Bonjour3
Bonjour4

I'm testing this little code for another program and I don't get why the arrays don't change. In my other program I can't access the double pointer or print the content. so my question is : why in this program I can't modify the content of the arrays ?

Reading Data from CSV to Screen output

This may not be allowed but I'll ask anyway.

I'm trying to develop a product similar to YALV but for a custom logs.

I have a CSV file that I want to read in and display on screen in a table that can be scrolled, filtered, coloured, etc similarly to YALV.

I have code for reading and deciphering the CSV and outputting in a neat format to another file. I want to adapt this to get it to screen.

I have experience in C# and C but only console related. Could someone guide me int he right direction to at least get the file being read in a Window in a similar format to YALV? What would be my possible steps? I'm unsure where to start....

Thanks

malloc can't create space for struct in queue

I tried to create a queue which contains 2 int values. The problem happens in insert function. When i try to allocate memory for head->front->next program halts. The error happens only in else part in insert function.

struct Patient{
   int national_id;
   int condition;
};

struct Node{
   struct Patient *info;
   struct Node *next;
};

struct Queue{
   int total;
   struct Node *rear;
   struct Node *front;
   int insert_number;
};

void insert (struct Queue *head, int natid, int cond);
void pop_min(struct Queue *head);
struct Queue *create_queue(void);
void destroy_queue(struct Queue *head);
void read_file(struct Queue *head);
void print_natid(struct Node *node);
void pop_all_elements(struct Queue *head);

void main(){
   struct Queue *head;

   head=create_queue();
   read_file(head);
   pop_all_elements(head);
   destroy_queue(head);
}

struct Queue *create_queue(void){

   struct Queue *head =(struct Queue*) malloc(sizeof(struct Queue));
   head->total=0;
   head->insert_number=0;
   return head;

}

void print_natid(struct Node *node){
   printf("%d ",node->info->national_id);
}


void insert (struct Queue *head,int natid, int cond){

   if(head->total==0){
      head->front=(struct Node*)malloc(sizeof(struct Node));
      head->front->info->national_id=natid;
      head->front->info->condition=cond;
      head->rear=head->front;
   }
   else{

      head->front->next=(struct Node*)malloc(sizeof(struct Node));
      head->front->next->info->national_id=natid;
      head->front->next->info->condition=cond;
      head->front=head->front->next;
   }


   head->insert_number++;
   head->total++;

   if(head->insert_number==3){
      pop_min(head);
      head->insert_number=0;
   }

   print_natid(head->rear);

}

void pop_min(struct Queue *head){

   printf("%d ",head->rear->info->national_id);

   struct Node *temp=head->rear;
   head->rear=head->rear->next;

   free(head->rear);
   free(temp);
}

void destroy_queue(struct Queue *head){
   free(head);
}

void pop_all_elements(struct Queue *head){
   struct Node *temp;

   while(head->rear!=head->front){
      print_natid(head->rear);
      temp=head->rear;
      free(temp);
      head->rear=head->rear->next;
   }

   print_natid(head->rear);
   free(head->rear);

}

void read_file(struct Queue *head){
   FILE *fp;
   int natid;
   int cond;
   fp=fopen("patients.txt","r");

   while (fscanf(fp,"%d %d", &natid, &cond) ==2)
      insert(head,natid,cond);

   fclose(fp);
}

Compiling output to a file using DSH

I've written a small C program (more like a script really) that gathers some general system information from a machine and prints it out (cpu, ram, system temperature, etc). I'm trying to gather this information for a large group of machines, so I'm using dsh to do so. This all works fine, and running the program through dsh prints the desired output to the screen.

However, I want to compile this output from all the machines using dsh into a single file. I thought that simply using 'program >> output' as my command for dsh would work, but since dsh runs in parallel the output just gets garbled up.

Is there a way to run dsh so that the nodes don't run in parralel, but wait for total completion before moving on? Or, is there a better way to output this information to a file entirely?

Caputre string key with terminfo in C program

Nobody know a good way to take the terminfo key string in a C program? Like the infocmp of ncurses. I can't find anything :(

If someone know and want to tell me, i'll be very thanksfull

Have a nice day

typedef struct name name without a subsequent struct definition

I found the following code at lines 153-154 in the libelf.h of the libelf library:

/* Descriptor for the ELF file.  */
typedef struct Elf Elf;

I was looking for a struct definition of Elf but did not find it.

Later in the code, Elf is used, e.g.

/* Return descriptor for ELF file to work according to CMD.  */
extern Elf *elf_begin (int __fildes, Elf_Cmd __cmd, Elf *__ref);

In the thread Why should we typedef a struct so often in C?, user "unwind" says:

Also note that while your example (and mine) omitted naming the struct itself, actually naming it is also useful for when you want to provide an > opaque type. Then you'd have code like this in the header, for instance:

typedef struct Point Point;

Point * point_new(int x, int y);

and then provide the struct declaration in the implementation file.

Yet, I couldnt find a definition of the struct Elf in any c file either.

What am I missing? What is the purpose of a typedef struct Name_xy Name_xy; without struct definition? Or is this impossible and I just did not find the struct definition?

Have C generate an error inside a _Generic

I've been working on some code (related to linear algebra). I have a number of types that one should be able to multiply with each other.

Naturally I thought "let's use _Generic" for this. Well it works, as long as the combination of argument types are valid. According to search engines, some libraries have resorted to using attributes on dummy functions to generate errors:

#include "stdio.h"

// Example struct.
typedef struct mat3_s
{
    float m[9];
} mat3;

// Dummy function.
mat3 mult(mat3 const *A, mat3 const *B)
{   
    return *A;
}

mat3 mults(mat3 const *A, float const *B)
{
    return *A;
}

typedef mat3 (*dummyptr)(void *A, void *B);
extern dummyptr INCOMPATIBLE_TYPES() __attribute__((error("Crikey"))); 

#define LMULT(A, B)\
    _Generic((A),\
    mat3: \
        _Generic((B),\
            mat3: mult, \
            float: mults, \
            default: INCOMPATIBLE_TYPES()),\
    default: INCOMPATIBLE_TYPES()) (&(A), &(B))

int main(int argc, char *argv[])
{
    mat3 a = {{0}};
    mat3 b = {{0}};
    mat3 c = LMULT(a, b);

    mat3 d = LMULT(a, "not kosher");

    // Inhibit GCC from optimising away above variables.
    printf("%p %p %p %p\n", &a, &b, &c, &d);
    return 0;
}

The gymnastics involved is the "INCOMPATIBLE_TYPES" function. As it stands it doesn't work well (if at all). And it is GCC only, and fragile, and... just not nice.

_Pragma("gcc error \"Great heavens\"") will not work either since GCC expands _Pragma to the resulting macro. And that happens to be inside a _Generic-expression which of course is processed at a later stage.

I am about to give up and just give gibberish back (also called C++ error reporting) and hopefully it will give enough information as to what might be the problem.

Does anybody else have any ideas how to generate a user friendly enough message if two types are passed for which there is no corresponding function?

Handling loops in Brainf*ck

I tried testing my Brainfuck interpreter in c with this bottle shaped code in Brainfuck:

                +>+++++++[>>>+++
                 +++++<<<<+++++
               +++>-]+++++++++>>>
                +>>++++++++++[>+
                 +++++++++<-]>[
                 >>+>+>+>+>+>+>
                 +>>+>+>>+>+>+>
                 +>>+>+>>+>+>+>
                 >+>+>+>+>>>>>+
                 >+>+>+>>+>+>+>
                 >+>+>+>+>>+>+>
                +>>+>+>+>+>>+>+>
                >+>+>+>+>+>+>>>>
                +>+>>+>+>+>+<<<<
                <<<<<<<<<<<<<<<<
               <<<<<<<<<<<<<<<<<<
               <<<<<<<<<<<<<<<<<<
               <<<<<<<<<<<<<<<<<<
               -]<++++[>++++++++<
               -]>[>+>>>>>>>>+>>>
               +>>>>>+>>>+>>>>+>>
              >>>+>+>>+>>>>>+>>>>+
              >>>>>+>>>>+>>>>>+>>>
              +>>>>>>>+>+>+>>>+>>>
              >>+<<<<<<<<<<<<<<<<<
              <<<<<<<<<<<<<<<<<<<<
             <<<<<<<<<<<<<<<<<<<<<<
            <<<<<<<<<<<<<<<<-]+++++[
           >>>++>+++>+++>++>>+++>>++>
          >>>>>+++>>++>++>>+++>+>>>+++
        +>->++>++>++>+++>++>>--->->+>>>+
       +>++>>>>++>++++>++>>->++>>>++>->++
     +>+++>>+>+++>>>+++>++>+++>++>>>++>>++>
    ++>>++>++>+++<<<<<<<<<<<<<<<<<<<<<<<<<<<
   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  <<<<-]>>-->+>+>+>-->+>>>+>++>>-->+>+>->>+>>>
  +>->+>>->++>-->-->++>->>>->++>++>+>>+>>+>>>+
 >->>>++>>>>++>++>>>>>+>>++>->+>++>>>>+++>>>+>>
 ->+>->+<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<[>>>>++
++++++++[->[-]+>[-]<<[<<<<<.>>>>.>>>>.>.>.>.>.>.
>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>>
>.<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<.>>>>.>
>>>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>>>>>>>>>>>>>>
.>.>>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.
>.>.>.>.>.>.>.>.>.>.>.>.>.<<<<<<<<<<<<<<<<<<<<<<
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
<<<<.>>>>-.>>>>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.
>.>.>.>.>.>.>.>.>.>.>.>>.>..<<<<<<<<<<<<<<<<<<<<
<<<<<<<<<<<<-]>[<<<<<->[-]+>[-]<<[<.>>>>.>>>>.>.
>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.
>.>.>.>>>.<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
<.>>>>.>>>>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>>>>>>
>>>>>>>>.>.>>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.
>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.<<<<<<<<<<<<<<
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
<<<<<<<<<<<<-.>>>>+++++++++.>>>>.>.>.>.>.>.>.>.>
.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>>.>..<<<
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-]>[<<.>>>>.>>>
>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.
>.>.>.>.>.>>>.<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
<<<<<.>>>>.>>>>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>>
>>>>>>>>>>>>.>.>>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.
>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.<<<<<<<<<<
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
<<<<<<<<<<<<+++++++++.>>>>.>.>.>.>.>.>.>.>.>.>.>
.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>>.>..<<<<<<<<<
<<<<<<<<<<<<<<<<<<<<<<<<<<<->]<<+>>>>>->]<<]<<<<
-]>>>>++++++++[->[-]+>[-]<<[<.>>>>.>.>.>.>.>.>.>
.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>>>.<
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<.>>>>.>.>.>.>.
>.>.>.>.>.>.>.>.>.>.>.>>>>>>>>>>>>>>.>.>>.>.>.>.
>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.
>.>.>.>.>.>.>.<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-.>>>>.>.>.>
.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>
.>>.>..<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-]>[<<.>>
>>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>
.>.>.>.>.>.>>>.<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
<<.>>>>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>>>>>>>>>>
>>>>.>.>>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.
>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.<<<<<<<<<<<<<<<<<<
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
<<<<-.>>>>.>.>.>.>.>.>.>>.>.>.>.>.>.>.>.>.>.>.>.
>.>.>.>.>.>.>.>.>>.>..<<<<<<<<<<<<<<<<<<<<<<<<<<
<<<<<<->]<<]<.>>>>.>.>.>.>.>.>.>>.>.>.>.>.>.>.>.
>.>.>.>.>.>.>.>.>.>.>.>.>.>>>.<<<<<<<<<<<<<<<<<<
<<<<<<<<<<<<<<<<<.>>>>.>.>.>.>.>.>.>>.>.>.>.>.>.
>.>.>>>>>>>>>>>>>>.>.>>.>.>.>.>.>.>.>.>.>.>.>.>.
>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.
>.>.>.>.>.<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<.>.>.>.>.>.>.
 >.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>>.>

And instead ouf outputing the whole '99 bottles of beers on the wall' song from 99 to 1, it put out just the verses from 99 to 96 bottles. Is there something wrong with the loops in Brainfuck code or in the interpreter?

Here is my c code:

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

int loop(char *commands, int indexOfCommand, int mode){
    int sum = 0;
    int movingIndex = indexOfCommand;
    while(sum > -1){
        movingIndex -= mode;
        if(commands[movingIndex] == ']') 
            sum += mode;
        else if(commands[movingIndex]=='[')
            sum -= mode;
    }
    return movingIndex;
}

int main(){
    unsigned char array[30000] = {0}; // all elements are 0
    unsigned char commands[60000] = {0}; // all elements are 0
    int counter = 0;
    int c;

    int loop(char *commands, int indexOfCommand, int mode);

    while((c = getchar()) != EOF){
        commands[counter] = c;
        counter++;
    }   

    int indexOfArray = counter;
    int indexOfCommands = 0;
    int numOfCommands = 0;

    int length = sizeof(commands)/sizeof(commands[0]); // the length of an array

    while (indexOfCommands < length && numOfCommands < 60000){
        switch(commands[indexOfCommands]){
            case '+':
                if(array[indexOfArray]==255){
                    array[indexOfArray]=0;
                } else array[indexOfArray]++;
            break;
            case '-':
                if(array[indexOfArray]==0){
                    array[indexOfArray]=255;
                }else array[indexOfArray]--;
            break;
            case '>':
                indexOfArray++;
            break;
            case '<':
                indexOfArray--;
            break;
            case '.':
                putchar(array[indexOfArray]);
            break;
            case ']':
                if(array[indexOfArray]!=0) {
                    indexOfCommands=loop(commands,indexOfCommands,1);
                }
            break;
            case '[':
                if(array[indexOfArray]==0){
                    indexOfCommands=loop(commands,indexOfCommands,-1);
                }
            break;
            default:
                // if there is any other character, just ignore it
                break;
        }
        indexOfCommands++;
        numOfCommands++;
    }

    return 0;
}

Error with binary file

#include<stdio.h>
#include <string.h>
void main()
{
    FILE *f = fopen("F:\\hongphat.txt","wb+");
    char *password = "password";
    int l = strlen(password);
    fwrite(&l, sizeof(int), 1, f);
    fwrite(&password, 1, strlen(password), f);
    fclose(f);

    FILE *g = fopen("f:\\hongphat.txt", "rb+");
    char *passwordsame = new char[250];
    int length;
    fread(&length, sizeof(int), 1, g);
    fread(passwordsame, length, 1, g);
    int k = strlen(passwordsame);
    fclose(g);
    delete[]passwordsame;
}

i code this example to make a password for a file, but when i did that, i see that k is not equal to length ( length = 8), can anyone show my mistake

Distinguish between Signal type - SIGUSR1 vs SIGUSR2

I have a main in which 2 signals SIGUSR1 & SIGUSR2 are being sent using kill() to children pid1 and pid2. The signals are sent one after the other:

kill(pid1, SIGUSR1);
kill(pid2, SIGUSR2);

Using code below does not work:

 signal(SIGUSR1, handler);
 signal(SIGUSR2, handler);

How can I distinguish which signal was generated in pid1 and pid2?

Thanks.

How to load comments in a post details view?

i have been trying for over 2 months now but to no avail on how to load the comments with a specific blog post. For example: when you go to the index page of the blog, you will see the list of all blogpost... Now, when you click on a particular one, it will go to the details page. How do you, load the comments of that post to go together with the post in the details view and how to include a textbox underneath for new comment and not a new view page for new comment. Please, help me because at this point i have four things i can't get my head on and begining to loose interest in visual studio

How do I print out every string in a char** to printf()?

I have a main() routine which takes in all the command line arguments as a 'char **'. How do I display every one of the arguments in the console using printf()?

Thanks!

lexical analysis stops after yy_scan_string() is finished

I use flex to make a lexical analyzer. I want to analyse some define compiler statements which are in the form: #define identifier identifier_string. I keep a list of (identifier identifier_string) pair. So when I reach in the file a identifier that is #define list I need to switch the lexical analysis from main file to analyse the corresponding identifier_string. (I don't put the complete flex code because is too big) here's the part:

{IDENTIFIER}                    {   // search if the identifier is in list
                                    if( p = get_identifier_string(yytext) )
                                    {
                                        puts("DEFINE MATCHED");
                                        yypush_buffer_state(yy_scan_string(p));
                                    }
                                    else//if not in list just print the identifier
                                    {
                                        printf("IDENTIFIER %s\n",yytext);
                                    }
                                }
<<EOF>>                         {
                                    puts("EOF reached");
                                    yypop_buffer_state();
                                    if ( !YY_CURRENT_BUFFER )
                                    {
                                        yyterminate();
                                    }
                                    loop_detection = 0;
                                }

The analysis of the identifier_string executes just fine. Now when the EOF is reached I want to switch back at the initial buffer and resume the analysis. But it finishes just printing EOF reached.

SSL Connect error with libcurl after SKIP_PEER_VERIFICATION?

I am trying to connect to server which demands client authentication. I am doing it in C with libcurl. The problem is when I try to connect I get: curl_easy_perform() failed: SSL connect error I read that I should add server certificate to ca-bundle.crt; however server's certificate is self signed so when I add it to ca-bundle I got SSL peer certificate or SSH remote key was not OK. After that I tried do set CURLOPT_SSL_VERIFYPEER to false; but I got the first error curl_easy_perform() failed: SSL connect error This is my current code:

#define SKIP_HOSTNAME_VERIFICATION
#define SKIP_PEER_VERIFICATION

int authenticate(CURL *curl) {
    char* pathToCert = "sslCert.pem";
    char* pathToKey = "privateKey.pem";
    curl_easy_setopt(curl, CURLOPT_SSLCERTTYPE, "PEM");
    int res = curl_easy_setopt(curl, CURLOPT_SSLCERT, pathToCert);
    if (res != CURLE_OK)
        fprintf(stderr, "curl_easy_perform() failed: %s\n",
            curl_easy_strerror(res));
    curl_easy_setopt(curl, CURLOPT_SSLKEY, pathToKey);
}


int main(int argc, char **argv) {
    CURL *curl;
    CURLcode res;

    curl_global_init(CURL_GLOBAL_DEFAULT);

    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "https://localhost:8443/RemSig/status");
        authenticate(curl);

#ifdef SKIP_PEER_VERIFICATION
        /*
         * If you want to connect to a site who isn't using a certificate that is
         * signed by one of the certs in the CA bundle you have, you can skip the
         * verification of the server's certificate. This makes the connection
         * A LOT LESS SECURE.
         *
         * If you have a CA cert for the server stored someplace else than in the
         * default bundle, then the CURLOPT_CAPATH option might come handy for
         * you.
         */
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
#endif

#ifdef SKIP_HOSTNAME_VERIFICATION
        /*
         * If the site you're connecting to uses a different host name that what
         * they have mentioned in their server certificate's commonName (or
         * subjectAltName) fields, libcurl will refuse to connect. You can skip
         * this check, but this will make the connection less secure.
         */
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
#endif

        /* Perform the request, res will get the return code */
        res = curl_easy_perform(curl);
        /* Check for errors */
        if (res != CURLE_OK)
            fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));

        /* always cleanup */
        curl_easy_cleanup(curl);
    }

    curl_global_cleanup();

    return 0;
}

Does someone know where could be problem? The server is running and can be accessed from different client and browser.

EDIT - SOLUTION

After adding curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); to my code I find out that the problem was in certificate path. In path to certificate ./ should be added, otherwise libcurl can not find the certificate.

How to know if a function is called in C with or without typecasting using gdb or any other tool?

I have a lib from which a function is called using function pointer, the function pointer is set by us in local code.

The issue is, i have assigned the pointer an address of a function which accepts arguments.

and i am suspecting that in lib the function is called without arguments i.e. after type casting it to some other type.

Now, i want to know by using gdb or any other tool weather the function is called with/without type cast. I do not have exact code for the lib but i do have the lib with debug flags.

To explain here is a code snippet:

typedef  int (*type1)(void);
typedef int (*type2)(int, int);

int calledFunc (int,int);

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

    t1 = (type1)&calledFunc;

   t1();

   ((type2)t1)(5,6);

  system("PAUSE");  
  return 0;
}

int calledFunc (int a, int b)
{
    printf("Function called=> %d\n",a+b);
    return (a+b);
}

In above code how we can deduce using gdb if CalledFunc is called with or without typecasting?

Creating and Passing of mxArray Data from other functions to Mex gateway function

Ok guys, I feel as if I'm falling into the rabbit hole...

To build an interface as a Matlab-Mex that receives several different messages which consist of complicated C-structs, I want to create the corresponding Mex-Structs each in different functions.

Is it somehow possible to pass 'mxArrays' that contain fields from user defined functions to the 'mexFunction()'?

I created functions that should be called inside of 'mexFunctions()' that should pass filled 'mxArray' Datatypes to the 'mexFunction()' as pointers but that didn't work.

E.g.

mxArray* createFoo();

Or

void createFoo(mxArray* myData);

Inside the 'mexFunction()' these 'createFoo()' functions couldn't pass the created data pointers back to the function. Inside them, creating of data did work, but the pointers they returned changed mysteriously because of e.g. 'myData = mxCreateDoubleMatrix()'.

The Compiler is Visual Studio 2010.

It would be possible to directly write to workspace inside the functions, but that is very bad style.

I need help coding this calculation

This is math calculation that i need to program - define sequence an as

  • a1 = 1
  • a(n+1) = 1 / (2 × [an] - an + 1) where [x] is the floor function

If a2014 = p/q, find p + q

And, this is the code I tried:

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

main() {
   int n=1;
   double an=1.0;
   double an_floor=0.0;

   while (n<=2014) {
      an_floor = floor(an);
      an = 1 / (2*an_floor-an+1);
      n = n + 1;
   }

   printf("%lf", an);

   return 0;
}

Problems;

  • I cannot compile (using web complier such as codepad, etc.)

  • Don't know how to make result

  • Fraction result is wrong

Rearrange neighborhood numbers based on the removal between them

Suppose that the matrix A is stored N real. Reorder items of A in such a way that the differences between neighboring data A [i] - A [i + 1] to is an increasing sequence of numbers.

For example, if the matrix A is

A [4] = {10, 2, 7, 4}

then possible rearrangements the table is:

{2, 7, 10, 4}, because (2-7 = 5) <(7-10 = 3) <(10-4 = 6):
{4, 10, 7, 2}, because (4-10 = 6) <(10-7 = 3) <(7-2 = 5)

the exercise is asking me to Construct C program where to place a table 15 random integers numbers which lie in the range [0,100]. in then construct a function which rearranges the numbers in ascending difference adjacent values.if someone can give me some piece of code cause i have tried everything

C wrong variable decrementing

So I am extremely confused right now. In the following code I initialize a for loop and attempt to decrement a size_t variable. However when doing this it appears that another size_t variable begins to decrement instead.

The code is as follows:

/**
 * sanitize_octet - Sanitizes a given octet for ipv4 calculation
 * requirements.
 *
 * @octet - Octet to be sanitized.
 *
 * returns:
 * NULL pointer - failure
 * Pointer to ret - success
 */
const char *sanitize_octet(const void *octet)
{
        char ret[4];
        size_t i = strlen(octet), j = i;

        if(i > 3) {
                printf("error: '%s' is not a valid octet.", (char *) octet);
                return NULL;
        }
        strcpy(ret, (char *) octet);
        while(i--) {
                if(!isdigit(ret[i])) {
                        printf("error: '%s' is not a valid octet.", ret);
                        return NULL;
                }
                if((int) ret[i] > 255) {
                        printf("error: '%s' is not a valid octet.", ret);
                        return NULL;
                }
        }
        if(j != 3) {
                i = 3 - j;
                for(j = 2; j > 1; j--) {
                        printf("j: %d, i: %d\n", j, i);
                        system("pause");
                }
        }
        puts(ret);
}

The function is still a work in process. What is really confusing me is this the for loop at the bottom. When initialized as for(j = 2; j > 1; j-- it actually decrements i instead of j and will simply execute until it crashes. However if I initialize the loop with j having a different value (e.g. 3) it executes as expected. I've never seen anything like this before and am extremely confused.

Here is a sample console output with j initialized to 2:

j: 2, i: 2
Press any key to continue . . .
1




j: 2, i: 1
Press any key to continue . . .
19

You can clearly see that i is being decremented and not j.

What could possibly be causing this?

Backtracking all answers

I have this code here. It works fine when you're solving for a solution to a sudoku problem.

int solveBoard(int board[SIZE][SIZE], int rowPos, int colPos) {
    int newValueToCheck, oldRowPos, oldColPos;
    if (rowPos == SIZE) return 1;
    if (board[rowPos][colPos] != 0) {
        if (colPos == SIZE - 1) {
            rowPos++;
            colPos = 0;
        } else colPos++;
        if (solveBoard(board, rowPos, colPos) == 1) return 1;
        return 0;
    } for (newValueToCheck = 1; newValueToCheck <= SIZE; newValueToCheck++)
        if (checkBoard(board, newValueToCheck, rowPos, colPos) == 1) {
            board[rowPos][colPos] = newValueToCheck;
            oldRowPos = rowPos; 
            oldColPos = colPos;
            if (colPos == SIZE - 1) {
                rowPos++;
                colPos = 0;
            } else colPos++;
            if (solveBoard(board, rowPos, colPos) == 1) return 1;
            rowPos = oldRowPos;
            colPos = oldColPos;
            board[rowPos][colPos] = 0;
        }
    return 0;
}

Only thing is, I'd like to get all possible answers. How will I modify this and get all the possible answers.

How I can add a adjancy list to a node of defined type in C?

I have a defined node type for graph node:

    struct node{
    int data;
    int neighboursNumber;
    node * neighbours;
    };

And I am trying to add for each node some neighbours like this:

    node * n1 = (node *)malloc(sizeof(node));
    n1->data = 1;
    n1->neighboursNumber = 2;
    n1->neighbours = (node *)malloc(sizeof(node) * n1->neighboursNumber);

    node * n2 = (node *)malloc(sizeof(node));
    n2->data = 2;
    n2->neighboursNumber = 1;
    n2->neighbours = (node *)malloc(sizeof(node) * n2->neighboursNumber);

    node * n3 = (node *)malloc(sizeof(node));
    n3->data = 3;
    n3->neighboursNumber = 1;
    n3->neighbours = (node *)malloc(sizeof(node) * n3->neighboursNumber);

    n1->neighbours[0] = n2;
    n1->neighbours[1] = n3;

    n2->neighbours[0] = n1;
    n3->neighbours[0] = n1;

But I get an error at building

 error C2679: binary '=' : no operator found which takes a right-hand operand 
 of type 'node *' (or there is no acceptable conversion)

Isn't that the correct way to do it?

How not to receive a char which is not a number in scanf for double values.

I want in this little piece of code to insert double values and get the returned values as written, but in case I enter another character, besides numbers, I want the returned value to be 0.

here is my code:

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

int LegalInputChecker(double Move);

int main()
{
    double Move;
    int res;
    scanf("%lf", &Move);

   res = LegalInputChecker(Move);

   return res;

}

int LegalInputChecker(double Move)
{

    if(Move-(int)Move == 0 && (Move>0 && Move<=7))
    return 1; 

    else if((Move<0 || Move>7) && (Move-(int)Move == 0))
    return 2; 

    else if(Move==0)
    return 3;  

    else
    return 0;

}

for some reason, when I enter a letter for example, I keep getting the returned value "3", whats the reason?

Why can't I use the whole char [] in while?

In Python, I can do:

str = "abcd"
while(str):
    print str

Although it's not very useful (iterating over the elements in the string is usually what's needed), the fact that it's possible makes me wonder why the equivalent in C is not, So:

char str[] = "abcd"
while(str[])
{
    do stuff
} 

When I try to compile:

isblank.c:11:13: error: expected expression
        while (str[])
                   ^
1 error generated.

And I am forced to add the index of the string in the expression, therefore forcing it to iterate over the elements of the string.

Why so?

CUDA - nvcc -G - if not working properly

I'm currently working on porting a lava flow model in CUDA (full code on github here: Full source of the CUDA-SCIARA Fv2 lava flow model . I'm facing a problem with an if construct inside a __device__ function.

Based on the current lava quantity and temperature it computes the new temperature and if it is lower than a constant parameter (the variable d_PTsol=1143.0) the lava is solified.

The problem in the code below is that is works perfectly if I compile with the -G options (for the generation of device code debug infos) but behave wrongly without.

double new_temp = d_computeNewTemperature(sommah,sommath);        
if(new_temp <= d_PTsol){
            printf("Solidified %.5f,%.5f\n",new_temp,d_PTsol);
            double newQuote = d_sbts_updated[d_getIdx(row,col,ALTITUDE)]+d_sbts_current[d_getIdx(row,col,THICKNESS)];
            //CODE FOR LAVA SOLIDIFICATION HERE
    }else{
           //there is lava and is not solidified -> activate this cell!
           adjustAdaptiveGrid(row,col);
 }

ouptutting something like this at a certain point of the simulation:

Solidified 1344.68654 1143.00000
Solidified 1343.99509 1143.00000
Solidified 1320.50061 1143.00000
Solidified 1325.53942 1143.00000

To make things more subtle the problem completly disappear if I change the the if condition to a strict inequality if(new_temp < d_PTsol).

Compilation is carried out with the following options and in separate compilation mode

-O3 -Xcompiler -fPIC -std=c++11

and linking using

--cudart static --relocatable-device-code=true -gencode arch=compute_35,code=compute_35 -gencode arch=compute_35,code=sm_35

Has someone faced a similar issue before? Am I doing something wrong?

UPDATE

The problem seem to be somehow related to the translation of the if else construct with the <= as condition. Translating

if(new_temp <= d_PTsol) {
        //solidification
}else{
        //something else
}

to

if(new_temp <= d_PTsol) {
        //solidification
}
if(!(new_temp <= d_PTsol)){
        //something else
}

makes the code work perfectly.

How can I use access method for file extension?

I use access in order to understand file is exist or not.

char file[100];
strcpy(file, "/home/asd/test.txt");
if(access(file, F_OK) >= 0)
{
    printf("file is exist \n");
}
else
{
    printf("file is not exist \n");
}

I try to understand is there any file with txt extension or not so I want to use this code for file extension not file name. How can I do that?

MPI C Tree Structured Global Sum

How do I pair processes using MPI in C? It's a tree structured approach. Process 0 should be adding from all of the other even processes, which they are paired with. I only need it to work for powers of 2.

Should I be using MPI_Reduce instead of MPI Send/Receive? If so, why?

My program doesn't seem to get past for loop inside the first if statement. Why?

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <mpi.h>

int main(void){
  int sum, comm_sz, my_rank, i, next, value;
  int divisor = 2;
  int core_difference = 1;

  MPI_Init(NULL, NULL);
  MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
  MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
  srandom((unsigned)time(NULL) + my_rank);
  value = random() % 10;

      //process should recieve and add
      if (my_rank % divisor == 0){

          printf("IF----");

          printf("Process %d generates: %d\n", my_rank, value);

          for (i = 0; i < comm_sz; i++)
          {
              MPI_Recv(&value, 1, MPI_INT, i, my_rank , MPI_COMM_WORLD, MPI_STATUS_IGNORE);
               sum += value;  
               printf("Current Sum=: %d\n", sum);

          }

          printf("The NEW divisor is:%d\n", divisor);
          divisor *= 2;
          core_difference *= 2;

      }

      //sending the random value - no calculation
      else if (my_rank % divisor == core_difference){
          printf("ELSE----");
          printf("Process %d generates: %d\n", my_rank, value);
          MPI_Send(&value, 1, MPI_INT, 0, 0, MPI_COMM_WORLD);
      }
      else
         if (my_rank==0)
            printf("Sum=: %d\n", sum);

  MPI_Finalize();

  return 0;
}

Timer to implement a time-out function

I'm writing a Windows (Win32) program in C, which features a worker thread to process data from a USB hardware device. The thread handling all works well, however I now need to add a timer to handle a timeout function. I don't need a callback function, just the ability to start a single shot timer, and to be able to test weather it's complete without sleeping, something like this:

start_timout(1000);   // 1 second

while (timer_is_running())
{
  doing stuff while waiting...
  .
  .
  .
}

do stuff after timer is finished...
.
.
.

This would be running inside the worker thread.

I've looked at SetTimer(), and have tried creating a callback function that simply sets a global flag, then test for the flag, but that never gets set. I'm not sure if this is because I don't have a message handler inside my thread.

Any suggestions welcome.. Cheers!

How to hide console cursor in c?

I have a simple C program that represents a loading screen within the console but I can't get the cursor to hide. I tried cranking up the speed of the sleep function so that the cursor timer would be reset and the cursor would be gone but that doesn't work.

Any tips on how to hide the cursor.

Code:

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

const int TIME = 1;

int main(int argc,char *argv[]){
    int i;
    while (1){
        printf("loading");
        for (i=0;i<3;i++){
            sleep(TIME);
            printf(".");
        }
        sleep(TIME);
        printf("\r");
        system("Cls");
        sleep(TIME);
    }
}

Tokenizer only prints the first token

I am having trouble building a tokenizer. I am new to c++ and was wondering if anyone could help.

When I run the program, I enter the user input as "x = a + 1". When i do this, the only token output is the x. I want to display "x\n = a\n +\n 1\n"

#include <iostream>
#include <string>
using namespace std;

int main(void)
{

 char *text = (char*)malloc ( 40 *sizeof( char ));
 cout << "Enter the first arrangement of data." << endl;
 cin >> text;
 char *token = strtok(text, " ");
 while ( token )
 {
     if ( strlen(token) > 0 )
     {
        printf(" %s", token);
     }
     token = strtok(NULL, " ");
 }
 return 0;
}

Same code, same input, but randomly different output? (memcpy related)

I have this code which is supposed to decode a string (tmp) that contains only 0s and 1s (each ASCII character has a binary code asigned). The problem is that if I run the program with the exact same input, the output is different after the first 10 decodes.

tmp[500] = "110100110111110110110001110000110011110010111101001010001000111001111010000000000100011100100011110011010011001001101001100011100100010111111011010100000100100110010111011010010101110101101000010100111000101011001011111011101010001010111010100110000111101000110111001000000101000101011001011001001111110010010010110110110110101111001111101110001110110000";
char code[256][100];
int of=0;
char new_text[100];
char *buffer;
buffer = (char*) malloc (sizeof(char));
int buffer_size, j;
for (j=0; j<256; j++) {
    buffer_size = strlen(final_code[j]);
    free(buffer);
    buffer = (char*) malloc (buffer_size+1);
    memcpy(buffer, tmp, buffer_size);
    buffer[buffer_size]=0;
    if (strcmp(buffer, code[j]) == 0) {
        new_text[of++] = j;
        printf("It's a Match! buffer=%s, code[%d]=%s\n", buffer, j, code[j]);
        break;
    }
}
strcpy(tmp, tmp+buffer_size);

(It is guaranteed that the encodings do not 'conflict', most of them have the same number of characters and there aren't codes with the same beggining, like '0001' and '00010'.)

I suspect the problem is related to the memcpy, but I can't see it. Also, when crashing, the value of buffer_size is 5, but strlen(buffer) is 6, which might be the error source. Any ideas?

A segmentation fault

I have try the following code to judge prime:

const int N = 200000;
long prime[N] = {0};
long num_prime = 0;
int is_not_prime[N]={1,1};
void Prime_sort(void)
{
    for( long i = 2 ; i<N ; i++ )
    {
        if( !is_not_prime[i] )
        {
            prime[num_prime++] = i;
        }
        for( long j = 0; j<num_prime && i*prime[i]<N ; j++ )
        {
            is_not_prime[i*prime[j]] = 1;
        }   
    }   
}

But when I run it, it cause a segmentation fault! That fault I have never meet.And I searched Google,and it explain segmentation fault as follow:

A segmentation fault (often shortened to segfault) is a particular error condition that can occur during the operation of computer software. In short, a segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed

But I don't know where cause this fault in my code.Please help me.

Pointer value in Mac OS - Get Value from queue

I've defined a struct like this:

typedef struct queue
{
    int front, count;
    int values[MAX];
}QUEUE;

And when i try to get the value in the front of the queue (passing it to a variable) i get an error: "illegal instruction:4"

The function getting the value is:

int front(QUEUE *q, int *x){
    int r=0;

    if(q->count==0) r=1;
    else{
        *x = q->values[q->front];
    }
}

In fact , this compiles at a linux environment.

What could be the cause of the problem?

PS.: I've had it run with sudo. It does not show the error, but doesn't output anything .

Thank you all for your help in advance.

where is the error in the code of string reverse.c programming?

I want to use pointers to reverse a string and store it to new Array but my code is not working:

#include<stdio.h>
#include<conio.h>
char A[80]="This is the String";
char B[160];
int main(){

  int size=(sizeof(A)/sizeof(A[0]));
  char *pA;
  char *pB;
  pA=A;
  pB=(B+size);
  puts(A);
  while(*pA!='\o')
  {
     *pB--=*pA++;
  }

  puts(B);

  return 0;
}

serveral Compile Errors when using GCC

I am trying to upload a solution to an OJ ,the judge uses GCC I have received the following errors and having no idea about them.

error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘{’ token
void insert(int in){
^

In function ‘main’:
error: ‘struct mymultiset_int’ has no member named ‘insert’
x.insert(t);
^

error: ‘struct mymultiset_int’ has no member named ‘getmax’
printf("%d\n",x.getmax());
^
error: ‘struct mymultiset_int’ has no member named ‘_delete’
x._delete(0);
^

My code looks like this:

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
int t;
#define swap(a,b) t=b,b=a,a=t
/*
when using swap, I use format like swap(x,y); or swap(x,y),
*/

struct mymultiset_int{
    int e[100000],end;
    void insert(int in){...}
    int getmax(){ return e[0]; }
    void _delete(int i){...}
}x;
int main(){
    x.end=0;memset(x.e,0,sizeof(x.e));
    int N,t;scanf("%d",&N);
    char i[2];
    while (N--){
        scanf("%s",i);
        if (i[0]=='A'){
            scanf("%d",&t);
            x.insert(t);
        }
        else{
            printf("%d\n",x.getmax());
            x._delete(0);
        }
    }
}

C linux regex performance issue

I'm creating a program that reads file line by line, match that line to regex and diplay how many lines has matched that regex. The problem is, this program is using pretty great precentage of CPU. 67.5% without valgrind and with valgrind 100.1% and it's very slow ~5 seconds for 84000 lines. And valgrind outputs below(input file is 84000 lines long).

Why is it using so much cpu ?.Why is it taking so long?. Is there any way to make it faster and use less memory, cpu? Thank you.

==10737== HEAP SUMMARY:
==10737==     in use at exit: 0 bytes in 0 blocks
==10737==   total heap usage: 42,200,387 allocs, 42,200,387 frees, 5,441,088,516 bytes allocated
==10737== 
==10737== All heap blocks were freed -- no leaks are possible
==10737== 
==10737== For counts of detected and suppressed errors, rerun with: -v
==10737== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)

Source code:

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

int check_regex(char* line);
void regex_test(const char* log_file);

int main(){
    regex_test("/var/log/syslog");
}

void regex_test(const char* log_file){
    printf("%s\n", log_file);
   FILE * fp;
   char * line = NULL;
   size_t len = 0;
   ssize_t read;
   int line_count=0;
   int match_count=0;
   fp = fopen(log_file, "r");
   if (fp == NULL)
       exit(EXIT_FAILURE);

   while ((read = getline(&line, &len, fp)) != -1) {
    // printf("%p\n", &line);
    if (check_regex(line))
    {
      match_count++;
    }else{
      printf("%s", line);
      printf("%d\n", line_count);
      // exit(0);
    }
    line_count++;
   }
   printf("%d/%d\n",match_count, line_count);
   fclose(fp);
   if (line)
       free(line);
}

int check_regex(char* line){
  regex_t regex;
  if (regcomp(&regex,"^(\\w+[ ]+[0-9]+ [0-9]+:[0-9]+:[0-9]+) [A-Za-z0-9-]+ [A-Za-z\\/]+\\[?[^]:]*\\]?: <?(\\w+)?>? ?(.+)$", REG_EXTENDED)) {
      printf("Could not compile regex\n");
      exit(1);
  }
  if (!regexec(&regex, line, 0, NULL, 0)) {
      // printf("Match\n");
      regfree(&regex);
      return 1;
  }
  else{
      // printf("No Match\n");
      regfree(&regex);
      return 0;
  }
}

multiple inputs by user dynamically at runtime

How can we take multiple number of integer inputs by user choice in c in runtime. Here the first line of the input is the number of test cases. Then I am calculating the sum of the input numbers in this case.

The test case :

Input

3
1 6 7
2 7 3 4
2 1

Output:

14
16
3

Can we modify scanf() in this way so it can process this dynamic inputs.

I can't take the line as a string input and then split them into numbers.

Can we use the space and \n both to decide the numbers as we do to take strings as input as an example: scanf("%[^\n]",&str);

Brainfuck interpreter in c printing trouble

So im trying to code a very very simple brainfuck interpreter in c, and i run into problems while trying to outprint certain characters by what i understand (please keep in mind i just started c so im not doing any complicated stuff with pointers yet)

This is all my code:

>   #include <stdio.h>


    int bla(char tabukaz[30000], int ukaz, int num) {
    int sum=0;
    int index=ukaz;
    while (sum>-1) {
        index-=num;
        if (tabukaz[index]==']') sum+=num;
        else if (tabukaz[index]=='[') sum-=num;
    }   
    return index;
    }

    int main () {
    int tab[30000];
    int tabukaz[30000];
    int c; 
    int i = 0; int ukaz = 0;
    unsigned char ch;
    for (int i = 0; i < 30000; i++) {
        tab[i]=0;
        tabukaz[i]=0;
    }
    while ((c=getchar())!=EOF) {

            ch = (unsigned char)c;
            if (ch == '>' || ch == '<' || ch == '+' || ch == '-' || ch == '.' || ch == '[' || ch == ']') {
                tabukaz[ukaz]=ch;
            } 


        switch (ch) {
            case '>': i++; break;
            case '<': i--; break;
            case '+': tab[i]++;break;
            case '-': tab[i]--; break;
            case '.': putchar(tab[i]); break;
            case '[':
                if (tab[i]==0) {
                    ukaz = bla(tabukaz, ukaz, -1);
                }
                break;
            case ']':
                if (tab[i]!=0) {
                    ukaz = bla(tabukaz, ukaz, 1);
                }    
                break;
            default: break;
        }

        ukaz++;

    }
    return 0;
}

This is the input in question (i tried to avoid the other text in the actual input (keep in mind everything down here is part of the input, even the unnecessary text) We got provided with a make file which will write the output into a text file, and compare it to a predefined text, the problem is my text file comes out as a binary file and i cant figure out why. The problem may be hidden in how i handle [ and ] as i didnt have that problem in the earlier tests without them

+++++ +++++             initialize counter (cell #0) to 10
[                       use loop to set 70/100/30/10
    > +++++ ++              add  7 to cell #1
    > +++++ +++++           add 10 to cell #2
    > +++                   add  3 to cell #3
    > +                     add  1 to cell #4
<<<< -                  decrement counter (cell #0)
]
> ++ .                  print 'H'
> + .                   print 'e'
+++++ ++ .              print 'l'
.                       print 'l'
+++ .                   print 'o'
> ++ .                  print ' '
<< +++++ +++++ +++++ .  print 'W'
> .                     print 'o'
+++ .                   print 'r'
----- - .               print 'l'
----- --- .             print 'd'
> + .                   print '!'
> .                     print '\n'

fscanf function doesn't read in c

I tried to read some data from file and insert it to queue, Insert function works well, and i tried to catch the error with printfs. I saw that in while() line there is error. The data in file forms like that

12345 2

11232 4

22311 4

22231 2

void read_file(struct Queue *head){
FILE *fp;
int natid;
int cond;
fp=fopen("patients.txt","r");

    while (fscanf(fp,"%d %d", natid, cond) != EOF)
        insert(head,natid,cond);

fclose(fp);}

C syntax: return with two comma separated values [duplicate]

This question already has an answer here:

I tried this code (in ideone)

#include <stdio.h>

int function()
{
  return (111, 222);
}

int main(void)
{
  printf(">>%d\n", function());
  return 0;
}

and suprisingly it compiles and outputs the value 222.

Why the C compiler allows the syntax return (a, b); ?

How to read array of struct of a bin file in C

I have this code that works for me:

 fp = fopen("person.dat", "rb");
    struct Person{
        int pnummer;
        char name[20];
        float lenght;
        float weight;
    };
    struct Person*object=malloc(sizeof(struct Person));
    fread(object, sizeof(struct Person), 1, fp);
    printf("%s\n%d\n%f\n%f\n",object->name,object->pnummer,object->lenght,object->weight);

Output: Andreas 660311 181.000000 82.000000

I would like to read an array of this struct. So that i can have 10 persons. How do I write the last 3 lines?

typedef struct{
    int pnummer;
    char name[20];
    float lenght;
    float weight;
}Person;
Person p_lista[10];

Asterisk create_stasis_message Invalid magic number

I stuck to send a stasis_message for a self made module to the ARI.

I try to use the code example from the documentation :

http://ift.tt/1EhASX6

I use asterisk 13 instead example (who use the 12), and some signature are changed.

Here is the initialisation :

struct stasis_topic *foo_topic;

static int load_module(void)
{
    //  Register to stasis.
    stasis_app_register(app, callback_stasis, 0);
    // Create a bridge on witch ARI can conenct.
    stasis_app_bridge_create("mixing", app, "11000");

    // Create the topic
    foo_topic = stasis_topic_create(app);
    return ast_register_application_xml(app, exec);
}

And the code method who is calling when phone arrive :

static int exec()
{
    publish_foo();
}

static void publish_foo()
{
   printf("Trace 1\n");

   char* test =  "dataToSend";
   RAII_VAR(struct stasis_message_type*, foo_type, NULL, ao2_cleanup);
   stasis_message_type_create(app, NULL, &foo_type);

   RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
   printf("Trace 3\n");
   msg = stasis_message_create(type, test);

   if (!msg)
      return;

    stasis_publish(foo_topic, msg);

    printf("PASSING MESSAGE 4\n");
}

I always get message like :

bad magic number 0x332065 for object 0x7f2ea5ab8ec5

And this error appends in the method stasis_create_message().

[Edit]

I do not understand the error and the cause any help is appreciated.

As suggest by arheops, there is the function who are created problem. Apparently my object cannot be convert to an Asterisk object. Probably the structure I need to send to the create_message_function must be on a astobj2 type.

static struct astobj2 *INTERNAL_OBJ(void *user_data)
{
        struct astobj2 *p;

        if (!user_data) {
                ast_log(LOG_ERROR, "user_data is NULL\n");
                return NULL;
        }

        p = (struct astobj2 *) ((char *) user_data - sizeof(*p));
        if (AO2_MAGIC != p->priv_data.magic) {
                if (p->priv_data.magic) {
                        ast_log(LOG_ERROR, "bad magic number 0x%x for object %p\n",
                                p->priv_data.magic, user_data);
                } else {
                        ast_log(LOG_ERROR,
                                "bad magic number for object %p. Object is likely destroyed.\n",
                                user_data);
                }
                ast_assert(0);
                return NULL;
        }

        return p;
}

And the struct of astobj2 definition :

struct astobj2 
{    
   struct __priv_data priv_data;
   void *user_data[0];
};

I tried to create a a2object like describe here :

enter link description here

And I get an error :

*** Error in `asterisk': free(): invalid pointer:

Thanks

How to insert data into compiled binary for MCU

I am trying to insert a md5 hash of part of my binary into the binary, for keeping track of MCU FW version.

I have approached it like this: in the link script I have split the flash in two sections

MEMORY                                                                                                  
{                                                                                                       
FLASH0 (rx)      : ORIGIN = 0x8000000, LENGTH = 64K - 16                                                
FLASH1 (r)       : ORIGIN = 0x800FFF0, LENGTH = 16                                                      
RAM (xrw)      : ORIGIN = 0x20000000, LENGTH = 8K                                                       
} 

Then I have specified a output section like so:

  .fw_version :                                                                                         
  {                                                                                                     
    KEEP(*(.fw_version))                                                                                
  } >FLASH1

Next I have my firmware_version.c file containing only:

#define FW_VERSION_SIZE 16                                                                              

const unsigned char FW_VERSION[FW_VERSION_SIZE]                                                         
  __attribute__((section(".fw_version"), used)) = {0};

Then after the binary is compiled and objcopy has been used to create a .bin file I have a 65536 B large file, I split that file at 65520 bytes, do a md5 checksum of the first part and insert that into the second part (16 B). Lastly I do cat parta partb > final.bin.

When i examine this binary with hexdump I can see that the md5 checksum is indeed at the end. Using objdump -h I get:

...
8 .fw_version   00000010  0800fff0  0800fff0  00017ff0  2**2
...

and objdump -t gives:

...
0800fff0 g     O .fw_version    00000010 FW_VERSION
...

I thought that this meant that I could just use FW_VERSION[i] to get part i of the md5 checksum from within the mcu fw but when I examine the memory in gdb I get that it's all zeroed out like it was never changed.

What am I missing here?

[edit] the device is a stm32f030c8t6 arm cortex m0 programmed through gdb.

Enter a key to continue function

I wanna write a program for my personal introduction. So I wanna display it one by one by pressing enter key as name then place where I live then hobbies nd so one so how can it be possible? Along with this I wanna use sleep and system(CLS) function together.

How to store WCHAR value in PCHAR?

From my program I have received value of WCHAR word = "C:" but i am not able to store "C:" in PCHAR parm. Whenever i try to read value it always read only "C".(C language)

i tried typecasting (WCHAR *)parm = word; - failed(showed error) Pls do me a needful help.

How to escape from hex to decimal

I apologise if this is an obvious question. I've been searching online for an answer to this and cannot find one. This isn't relevant to my code per se, it's a curiosity on my part.

I am looking at testing my function to read start and end bytes of a buffer.

If I declare a char array as:

char *buffer;
buffer = "\x0212\x03";

meaning STX12ETX - switching between hex and decimal.

I get the expected error:

warning: hex escape sequence out of range [enabled by default]

I can test the code using all hex values:

"\x02\x31\x32\x03"

I am wanting to know, is there a way to escape the hex value to indicate that the following is a decimal value?

memset fill file with 'a'

Almost two hours I'm having problems with my program. I'm trying to fill my file with character 'a'but my program doesn't work. Here's my write function

int da_aio_write(const int d, struct aiocb *aiorp, void *buf, const int count){
   int rv = 0;

   memset( (void *)aiorp, 'a', sizeof( struct aiocb ) );
   aiorp->aio_fildes = d;
   aiorp->aio_buf = buf;
   aiorp->aio_nbytes = count;
   aiorp->aio_offset = 0;
   rv = aio_write( aiorp );

   if( rv == -1) {
       perror("ERROR!!!\n"); // my program print this (Invalid argument)
       exit(1);
       return rv;
   }
   return rv;
}

somehow rv fail (rv == -1) and I don't get expected results. Alsko I add my full program

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <string.h>
#include <aio.h>

#define MB 1024

int da_open(const char *name);
int da_aio_write(const int d, struct aiocb *aiorp, void *buf, const int count);
int da_test_wait( struct aiocb *aiorp );
int da_close(int fd);

int da_open(const char *name){
   int dskr;
   int dskr2;
   dskr = open( name, O_RDWR );
   if( dskr == -1 ){
       printf("Failas sukurtas, nes jo nebuvo\n");
       dskr2 = open( name, O_WRONLY | O_CREAT, 0644);
   }else{
       printf("Toks failas jau yra!\n");
       exit(1);
   }
   printf( "dskr1 = %d\n", dskr2 );
   return dskr2;
}

int da_aio_write(const int d, struct aiocb *aiorp, void *buf, const int count){
   int rv = 0;

   memset( (void *)aiorp, 'a', sizeof( struct aiocb ) );
   aiorp->aio_fildes = d;
   aiorp->aio_buf = buf;
   aiorp->aio_nbytes = count;
   aiorp->aio_offset = 0;
   rv = aio_write( aiorp );

   if( rv == -1) {
       printf("ERROR!!! ");
       exit(1);
       return rv;
   }
   return rv;
}

int da_test_wait( struct aiocb *aiorp ){
   const struct aiocb *aioptr[1];
   int rv;
   aioptr[0] = aiorp;
   rv = aio_suspend( aioptr, 1, NULL );
   if( rv != 0 ){
      perror( "aio_suspend failed" );
      abort();
   }
   rv = aio_return( aiorp );
   printf( "AIO complete, %d bytes write.\n", rv );
   return 1;
}

int da_close(int fd){
   int rv;
   rv = close( fd );
   if( rv != 0 ) perror ( "close() failed" );
   else puts( "closed" );
   return rv;
}

int main(int argc, char *argv[] ){
    int sk;
    int d;
    struct aiocb aior;
    if(argc == 3){
        sk = atoi(argv[2]);
        char buffer[MB * MB * sk];
        memset(buffer, 0, sizeof buffer);
        d = da_open(argv[1]);
        da_aio_write( d, &aior, buffer, sizeof(buffer) );
        da_test_wait( &aior );
        da_close( d );
    }
    return 0;
}

Drop sniffed packet on matching content

I have made a packet sniffer in C using rawsockets that sniffs all outgoing UDP traffic on a specified port.

I now want to drop certain outgoing UDP packets that match a certain payload, so that they can be resent with a different payload.

A sniffer will no longer be useful in this situation, because it seems unable to motify the network traffic it detects.

Is there a way to drop packets that match a certain payload and port on a Linux system without modifying kernel code? Is my sniffer useless for the goal I have?

Undefined reference to google::protobuf::internal::empty_string_[abi:cxx11]

I'm trying to build simple test application with Protocol Buffers 2.6.1 and GNU GCC 5.1.0 (on Ubuntu 14.10) and I get following errors:

/home/ragnar/cpp-tools/gcc-linux/bin/g++   -c  "/home/ragnar/cpp-projects/gprotobuf_test/main.cpp" -g -O0 -Wall   -o ./Debug/main.cpp.o -I. -I/home/ragnar/cpp-tools/libs/linux64/protobuf/include -I.
/home/ragnar/cpp-tools/gcc-linux/bin/g++   -c  "/home/ragnar/cpp-projects/gprotobuf_test/messages.pb.cc" -g -O0 -Wall   -o ./Debug/messages.pb.cc.o -I. -I/home/ragnar/cpp-tools/libs/linux64/protobuf/include -I.  
/home/ragnar/cpp-tools/gcc-linux/bin/g++  -o ./Debug/gprotobuf_test @"gprotobuf_test.txt" -L. -L/home/ragnar/cpp-tools/libs/linux64/protobuf/lib  -lprotobuf  
./Debug/main.cpp.o: In function google::protobuf::internal::GetEmptyStringAlreadyInited[abi:cxx11]():  
  /home/ragnar/cpp-tools/libs/linux64/protobuf/include/google/protobuf/generated_message_util.h:80: 
    undefined reference to google::protobuf::internal::empty_string_[abi:cxx11]  
  /home/ragnar/cpp-tools/libs/linux64/protobuf/include/google/protobuf/generated_message_util.h:81: 
    undefined reference to google::protobuf::internal::empty_string_[abi:cxx11]  
./Debug/messages.pb.cc.o: In function protobuf_AssignDesc_messages_2eproto():  
  /home/ragnar/cpp-projects/gprotobuf_test/messages.pb.cc:32: 
    undefined reference to google::protobuf::DescriptorPool::FindFileByName(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) const  
./Debug/messages.pb.cc.o: In function protobuf_AddDesc_messages_2eproto():  
  /home/ragnar/cpp-projects/gprotobuf_test/messages.pb.cc:83: 
    undefined reference to google::protobuf::MessageFactory::InternalRegisterGeneratedFile(char const*, void (*)(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&))  
./Debug/messages.pb.cc.o: In function my_message::MergePartialFromCodedStream(google::protobuf::io::CodedInputStream*):
  /home/ragnar/cpp-projects/gprotobuf_test/messages.pb.cc:187: 
    undefined reference to google::protobuf::internal::WireFormatLite::ReadString(google::protobuf::io::CodedInputStream*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >*)  
./Debug/messages.pb.cc.o: In function my_message::SerializeWithCachedSizes(google::protobuf::io::CodedOutputStream*) const:
  /home/ragnar/cpp-projects/gprotobuf_test/messages.pb.cc:247: 
    undefined reference to google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, google::protobuf::io::CodedOutputStream*)  
./Debug/messages.pb.cc.o: In function google::protobuf::internal::WireFormatLite::WriteStringToArray(int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, unsigned char*):
  /home/ragnar/cpp-tools/libs/linux64/protobuf/include/google/protobuf/wire_format_lite_inl.h:749: 
    undefined reference to google::protobuf::io::CodedOutputStream::WriteStringWithSizeToArray(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, unsigned char*)  
./Debug/messages.pb.cc.o:(.rodata._ZTV10my_message[_ZTV10my_message]+0x20): 
    undefined reference to google::protobuf::Message::GetTypeName[abi:cxx11]() const  
 ./Debug/messages.pb.cc.o:(.rodata._ZTV10my_message[_ZTV10my_message]+0x40): 
    undefined reference to google::protobuf::Message::InitializationErrorString[abi:cxx11]() const  
collect2: error: ld returned 1 exit status  
gprotobuf_test.mk:93: recipe for target "Debug/gprotobuf_test" failed  
make[1]: *** [Debug/gprotobuf_test] Error 1  
make[1]: Leaving directory "/home/ragnar/cpp-projects/gprotobuf_test"  
Makefile:4: recipe for target "All" failed  
make: *** [All] Error 2  

The /home/ragnar/cpp-tools/libs/linux64/protobuf/lib contains following libraries:

libprotobuf.a  
libprotobuf.so.9.0.1  
libprotobuf-lite.a  
libprotobuf-lite.so.9.0.1  
libprotoc.a  
libprotoc.so.9.0.1  

Here's the simple messages.proto file:

option java_package = "my.package";

message my_message {
  required string word = 1;
  required uint32 number = 2;
}

and the code I'm trying to get working:

#include <iostream>
#include <vector>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include "messages.pb.h"

std::vector<unsigned char> encode( google::protobuf::Message & msg )
{
  std::vector<unsigned char> data( msg.ByteSize() + 
    google::protobuf::io::CodedOutputStream::VarintSize32( msg.ByteSize() ) );
  google::protobuf::io::ArrayOutputStream array_out( &data[0], data.size() );
  google::protobuf::io::CodedOutputStream coded_out( &array_out );
  coded_out.WriteVarint32( msg.ByteSize() );
  msg.SerializeToCodedStream( &coded_out );
  return data;
}

void decode( const std::vector<unsigned char> & data, google::protobuf::Message & msg )
{
  google::protobuf::io::ArrayInputStream array_in( &data[0] , data.size() );
  google::protobuf::io::CodedInputStream coded_in( &array_in );
  google::protobuf::uint32 size;
  coded_in.ReadVarint32( &size );
  google::protobuf::io::CodedInputStream::Limit msg_limit = coded_in.PushLimit( size );
  msg.ParseFromCodedStream( &coded_in );
  coded_in.PopLimit( msg_limit );
}

int main(int argc, char **argv)
{
  my_message in_msg;
  in_msg.set_word( \"blah blah\" );
  in_msg.set_number( 123 );
  std::vector<unsigned char> data = encode( in_msg );

  my_message out_msg;
  decode( data, out_msg );
  std::cout << \"word: \" << out_msg.word() << \" number: \" << out_msg.number() << std::endl;
  return 0;
}

Gcc is built from source with following options:

--enable-64bit --enable-32bit --enable-languages=c,c++ --enable-multilib
--disable-nls --enable-threads=posix --enable-checking=release
--enable-lto --enable-multiarch --with-multilib-list=m32,m64,mx32 
--with-tune=generic --enable-shared --with-glibc-version=2.13
--enable-libstdcxx-time=rt

and Protobuf is built from source with following options:

--enable-64it --disable-32bit --enable-shared CXXFLAGS=-m64 -DNDEBUG LDFLAGS=-m64

Any help would be greatly appreciated.

Anagrams of two strings

Write C a program to find whether the 2 given strings are anagrams or not.

Input consists of 2 string. Assume that all characters in the string are lowercase letters or spaces and the maximum length of the string is 100.

Sample Input and Output 1: Enter the first string anitha Enter the second string amphisoft anitha and amphisoft are not anagrams

Sample Input and Output 2: Enter the first string the eyes Enter the second string they see the eyes and they see are anagrams

Sample Input and Output 3: Enter the first string dormitory Enter the second string dirty room dormitory and dirty room are anagrams

#include <stdio.h>

int check_anagram(char [], char []);

int main()
{
   char a[100], b[100];
   int flag;

   printf("Enter first string\n");
   gets(a);

   printf("Enter second string\n");
   gets(b);

   flag = check_anagram(a, b);

   if (flag == 1)
      printf("\"%s\" and \"%s\" are anagrams.\n", a, b);
   else
      printf("\"%s\" and \"%s\" are not anagrams.\n", a, b);

   return 0;
}

int check_anagram(char a[], char b[])
{
   int first[26] = {0}, second[26] = {0}, c = 0;

   while (a[c] != '\0')
   {
      first[a[c]-'a']++;
      c++;
   }

   c = 0;

   while (b[c] != '\0')
   {
      second[b[c]-'a']++;
      c++;
   }

   for (c = 0; c < 26; c++)
   {
      if (first[c] != second[c])
         return 0;
   }

   return 1;
}

I write the code but it was working only for first one input/output but second and third one input it was not working.