mardi 30 juin 2015

netBeans project, OSx, C executable claims dylib can not be found


It will not surprise me to find this is a duplicate but I have not found the dup yet...

I have a NetBeans "project" with three sub-projects... actually three connected, but separate projects: ProjectExectuable, libProject.a, and project.dylib.

  • "libProject.a" is a static library that compiles and uses ar and ran lib to build.
  • ProjectExecutable and project.dylib link against libProject

All three compile and build. When I try to execute ProjectExecutable I get the message:

dyld: Library not loaded: /usr/local/mysql/lib/libmysqlclient.18.dylib
Referenced from: /path/to/ProjectExecutable/dist/Debug/GNU-MacOSX/./ProjectExecutable
Reason: image not found
Trace/BPT trap: 5

There is no /usr/local/mysql on the machine. my local install path is: /usr/local/mysql-connector-c -- this is a symlink to a similar dir with a longer name that includes the version.

I am not, as far as I can tell, referencing the /usr/local/mysql/ path anywhere in the libProject or ProjectExecutable NB "projects". I have done a find with a grep on the workspace and only the binary executable and the created libs "match".


Why the code is working fine without mutex?


I am trying to learn how locks work in multi-threading. When I execute the following code without lock, it worked fine even though the variable sum is declared as a global variable and multiple threads are updating it. Could anyone please explain why here threads are working perfectly fine on a shared variable without locks?

Here is the code:

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

#define NTHREADS      100
#define ARRAYSIZE   1000000
#define ITERATIONS   ARRAYSIZE / NTHREADS

double  sum=0.0, a[ARRAYSIZE];
pthread_mutex_t sum_mutex;


void *do_work(void *tid) 
{
  int i, start, *mytid, end;
  double mysum=0.0;

  /* Initialize my part of the global array and keep local sum */
  mytid = (int *) tid;
  start = (*mytid * ITERATIONS);
  end = start + ITERATIONS;
  printf ("Thread %d doing iterations %d to %d\n",*mytid,start,end-1); 
  for (i=start; i < end ; i++) {
    a[i] = i * 1.0;
    mysum = mysum + a[i];
    }

  /* Lock the mutex and update the global sum, then exit */
  //pthread_mutex_lock (&sum_mutex);  //here I tried not to use locks
  sum = sum + mysum;
  //pthread_mutex_unlock (&sum_mutex);
  pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
  int i, start, tids[NTHREADS];
  pthread_t threads[NTHREADS];
  pthread_attr_t attr;

  /* Pthreads setup: initialize mutex and explicitly create threads in a
     joinable state (for portability).  Pass each thread its loop offset */
  pthread_mutex_init(&sum_mutex, NULL);
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  for (i=0; i<NTHREADS; i++) {
    tids[i] = i;
    pthread_create(&threads[i], &attr, do_work, (void *) &tids[i]);
    }

  /* Wait for all threads to complete then print global sum */ 
  for (i=0; i<NTHREADS; i++) {
    pthread_join(threads[i], NULL);
  }
  printf ("Done. Sum= %e \n", sum);

  sum=0.0;
  for (i=0;i<ARRAYSIZE;i++){ 
  a[i] = i*1.0;
  sum = sum + a[i]; }
  printf("Check Sum= %e\n",sum);

  /* Clean up and exit */
  pthread_attr_destroy(&attr);
  pthread_mutex_destroy(&sum_mutex);
  pthread_exit (NULL);
}

With and without lock I got the same answer!

Done. Sum= 4.999995e+11 
Check Sum= 4.999995e+11


Unable to print integer array


Im a newbie to "C" , I primarily migrated/re-implemeted "C" programs to Java, etc. I'm trying to learn "C" and I have gone through several tutorials. I have a program that attempts to read user input(numbers) from command line via "char *argv" , and sort those numbers & just print the sorted numbers out.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[])
{
        //if thee is argument supplied
        if (argc > 1)
        {
            int count = 0;
            //array to sort less 1
            count = argc -1;
            int tobe_sorted[count];
            int i=0;
            //allocate memory for target result array
            int *target = malloc(count * sizeof(int));
            //copy unsorted ints to target
            memcpy(target, tobe_sorted, count * sizeof(int));
            //sort target using bubble sort
            int temp =0;
            int x =0;
            int y=0;
            for (x=0; x<count; x++ )
            {
                for (y=0; y<count -1; y++ )
                {
                    if (target[i]>target[i+1])
                    {
                        temp = target[i+1];
                        target[i+1] = target[i];
                        target[i] = temp;

                    }
                }//end inner

            }//end outer

            //end bubble sort
            x=0;
            printf("Sorted:\n");
            //print sorted array
            while (x <count)
            {
                printf("%d",target[x]);
                printf(",");
                x++;
            }
             printf("\n");
        }//end argument supplied
        else{
            printf("Error, please enter numbers to be sorted\n");
        }

        return 0;
    }//end main function

My input :

PS C:\Users\xyz\workspace_cpp\the_hard_way\ex18> .\sort_test.exe 5 4 3 2 1

Output:

Sorted: 2686748,1986196690,32,1,4199492,

1) I'm not sure what "C" is printing out, are these ASCII codes? 2)What do I need to fix in the above program in order to print the sorted int array?

Disclaimer (Im not looking to use library functions such as qsort(), or to make the program more efficient).

Thanks a million!


How to check if a file is being used by another application?


I am using the following code to check if a file is being used by another application:

HANDLE fh = CreateFile("D:\\1.txt", GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
if (fh == INVALID_HANDLE_VALUE)
{
    MessageBox(NULL, "The file is in use", "Error", 0);
}

If the file is being used by another application, the message box is displayed. However, the message box is also displayed if the file does not exists!

So what should I do to solve this problem, should I also check if the file exists (using another function), or can the parameters of CreateFile() be changed to only return INVALID_HANDLE_VALUE if the file is in use and does exists?


realloc() on array of structs gives invalid next size


I have this function. As you can see, everything is being done in the function, I'm not allocating in the main and then passing anything to it (I'll only return the pointer to the array once the function is done). The function in itself (with a fixed size for the array) works, but the realloc fails.

struct database *parse() {

    int i = 0;
    int n = 1;

    FILE *dbase = (fopen(PATH, "r"));
    if (dbase == NULL) {
        fprintf(stderr, ERRORE_APERTURA);
        exit(EXIT_FAILURE);
    }

    struct database *database_array =  calloc(20*n, sizeof(struct database));
    if (database_array == NULL) {
        fprintf(stderr, "Impossibile allocare memoria\n");
        exit(EXIT_FAILURE);
    }

    while (feof(dbase) == 0) {
        fscanf(dbase, "%[^:]:%[^:]:\n", database_array[i].user, database_array[i].password);
        database_array[i].iswritten = 1;
        i++;
        if (i > 20*n) {
            n++;
            struct database *new_database_array = realloc(database_array, sizeof(struct database)*(20*n));
            free(database_array);
            database_array = new_database_array;
        }
    }
    database_array[++i].iswritten = 0;

    fclose(dbase);  
    return database_array;
}

I tried reading other explanations, but I can't understand what's wrong here.

The array I allocated with calloc is initially 20. then, when it's filled, I want it to double in size, so I use n, which will be 2, by 20, so 40.

The frustrating thing is that I tried reallocating an array of struct with a simpler program, and doing THE SAME THING works without any problem:

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

struct prova  {

    int a;

    int b[10];
};


int main() {

    struct prova* array_struct = calloc(10, sizeof(struct prova));

    array_struct[0].a = 2;

    struct prova* tmp = realloc(array_struct, sizeof(struct prova) * 20);

    free(array_struct);
    array_struct = tmp;

    array_struct[1].b[1] = 3;

    printf("a = %d", array_struct[0].a);
    printf("b = %d\n", array_struct[1].b[1]);

    return 0;   
}

What am I not seeing? (Please nevermind the fact that I'm not checking if realloc returns NULL, I'll add that later)


Execution Error in Greedy Gift Givers


This is the problem statement A group of NP (2 ≤ NP ≤ 10) uniquely named friends has decided to exchange gifts of money. Each of these friends might or might not give some money to any or all of the other friends. Likewise, each friend might or might not receive money from any or all of the other friends. Your goal in this problem is to deduce how much more money each person gives than they receive.

The rules for gift-giving are potentially different than you might expect. Each person sets aside a certain amount of money to give and divides this money evenly among all those to whom he or she is giving a gift. No fractional money is available, so dividing 3 among 2 friends would be 1 each for the friends with 1 left over -- that 1 left over stays in the giver's "account".

In any group of friends, some people are more giving than others (or at least may have more acquaintances) and some people have more money than others.

Given a group of friends, no one of whom has a name longer than 14 characters, the money each person in the group spends on gifts, and a (sub)list of friends to whom each person gives gifts, determine how much more (or less) each person in the group gives than they receive.

IMPORTANT NOTE

The grader machine is a Linux machine that uses standard Unix conventions: end of line is a single character often known as '\n'. This differs from Windows, which ends lines with two charcters, '\n' and '\r'. Do not let your program get trapped by this!

PROGRAM NAME: gift1

INPUT FORMAT

Line 1: The single integer, NP Lines 2..NP+1: Each line contains the name of a group member Lines NP+2..end: NP groups of lines organized like this: The first line in the group tells the person's name who will be giving gifts. The second line in the group contains two numbers: The initial amount of money (in the range 0..2000) to be divided up into gifts by the giver and then the number of people to whom the giver will give gifts, NGi (0 ≤ NGi ≤ NP-1). If NGi is nonzero, each of the next NGi lines lists the the name of a recipient of a gift. SAMPLE INPUT (file gift1.in)

5 dave laura owen vick amr dave 200 3 laura owen vick owen 500 1 dave amr 150 2 vick owen laura 0 2 amr vick vick 0 0 OUTPUT FORMAT

The output is NP lines, each with the name of a person followed by a single blank followed by the net gain or loss (final_money_value - initial_money_value) for that person. The names should be printed in the same order they appear on line 2 of the input.

All gifts are integers. Each person gives the same integer amount of money to each friend to whom any money is given, and gives as much as possible that meets this constraint. Any money not given is kept by the giver.

SAMPLE OUTPUT (file gift1.out)

dave 302 laura 66 owen -359 vick 141 amr -150

MY SOLUTION

#include<stdio.h>
#include<math.h>
#include<string.h>
int main(void)
{
    int n,i,j,k,money,people,tmoney[10],gmoney;
    char name[10][20],giver[20],reciver[20];
    FILE *fin=fopen("gift1.in","r");
    FILE *fout=fopen("gift1.out","w");
    //scanf("%d",&n);
    fscanf(fin,"%d",&n);
    for(i=0;i<n;i++)
        tmoney[i]=0;
    for(i=0;i<n;i++)
    fscanf(fin,"%s",(char *)&name[i][0]);
    //scanf("%s",&name[i]);
for(i=0;i<n;i++)
{
    //scanf("%s",giver);
    fscanf(fin,"%s",giver);
    //scanf("%d %d",&money,&people);
    fscanf(fin,"%d %d",&money,&people);
    gmoney=floor(money/people);
    j=0;        
    while(strcmp(giver,name[j]))
        j++;
    tmoney[j]+=money-(gmoney*people);
    for(k=0;k<people;k++)
    {
        //scanf("%s",reciver);
        fscanf(fin,"%s",reciver);
        j=0;
        while(strcmp(reciver,name[j]))
            j++;
        tmoney[j]+=gmoney;
    }


}

for(i=0;i<n;i++)
    fprintf(fout,"%s %d",&name[i][0],tmoney[i]);
    //printf("%s %d\n",name[i],tmoney[i]);
return 0;

}


Why is 0 moved to stack when using return value?


I'm experimenting disassembling clang binaries of simple C programs (compiled with -O0), and I'm confused about a certain instruction that gets generated.

Here are two empty main functions with standard arguments, one of which returns value and other does not:

// return_void.c
void main(int argc, char** argv)
{
}

// return_0.c
int main(int argc, char** argv)
{
    return 0;
}

Now, when I disassemble their assemblies, they look reasonably different, but there's one line that I don't understand:

return_void.bin:
(__TEXT,__text) section
_main:
0000000000000000    pushq   %rbp
0000000000000001    movq    %rsp, %rbp
0000000000000004    movl    %edi, -0x4(%rbp)
0000000000000007    movq    %rsi, -0x10(%rbp)
000000000000000b    popq    %rbp
000000000000000c    retq

return_0.bin:
(__TEXT,__text) section
_main:
0000000100000f80    pushq   %rbp                
0000000100000f81    movq    %rsp, %rbp          
0000000100000f84    xorl    %eax, %eax          # We return with EAX, so we clean it to return 0
0000000100000f86    movl    $0x0, -0x4(%rbp)    # What does this mean?
0000000100000f8d    movl    %edi, -0x8(%rbp)
0000000100000f90    movq    %rsi, -0x10(%rbp)
0000000100000f94    popq    %rbp
0000000100000f95    retq

It only gets generated when I use the function is not void, so I thought that it might be another way to return 0, but when I changed the returned constant, this line didn't change at all:

// return_1.c
int main(int argc, char** argv)
{
    return 1;
}

empty_return_1.bin:
(__TEXT,__text) section
_main:
0000000100000f80    pushq   %rbp
0000000100000f81    movq    %rsp, %rbp
0000000100000f84    movl    $0x1, %eax           # Return value modified
0000000100000f89    movl    $0x0, -0x4(%rbp)    # This value is not modified
0000000100000f90    movl    %edi, -0x8(%rbp)
0000000100000f93    movq    %rsi, -0x10(%rbp)
0000000100000f97    popq    %rbp
0000000100000f98    retq

Why is this line getting generated and what is it's purpose?


getting the value of compile-time expressions in C [duplicate]


This question already has an answer here:

Is there any way to have the C compiler (XC16 in my case, which is based on gcc) dump the results of compile-time expressions?

We have lots of #defines like

#define FOO 37.6
#define FOO_BASE 0.035
#define FOO_FIXEDPOINT (int16_t)(FOO/FOO_BASE)

and I would like to know the actual numbers that the compiler reduces these expressions to.

Note that this is NOT the same thing as wanting to know what the preprocessor outputs; the preprocessor does not compute math, it only substitutes in things. If I look at the preprocessor output, I get (effectively)

#define FOO_FIXEDPOINT (int16_t)(37.6/0.035)

and it's the compiler, not the preprocessor, which figures out a value.


Range of unsigned char in C language


As per my knowledge range of unsigned char in C is 0-255. but when I executed the below code its printing the 256 as output. How this is possible? I have got this code from "test your C skill" book which say char size is one byte.

main()
{
 unsigned char i = 0x80;
 printf("\n %d",i << 1);
} 


Time limit exceeded error when using strlen()?


The following code works as expected, this code prints the character that occurs the most number of times in a string:

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

int main() {

    long int i,a[26]={0},m=0 ,c=0 ;
    char s[1000001] ;
    scanf("%s",s);
    for (i=0;s[i]!='\0';i++){
        a[s[i]-'a']++;
    }
    for ( i=0 ; i<26 ; i++)
        {
            if ( a[i] > m ) {       
            m = a[i] ;
            c = i ;
            }
        }

    printf("%c",'a' + c);
    return 0;
}

but when I use strlen() it causes a time limit error:

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

int main() {

    long int i,a[26]={0},m=0 ,c=0 ;
    char s[1000001] ;
    scanf("%s",s);
    for (i=0;i<strlen(s);i++){
        a[s[i]-'a']++;
    }
    for ( i=0 ; i<26 ; i++)
        {
            if ( a[i] > m ) {       
            m = a[i] ;
            c = i ;
            }
        }

    printf("%c",'a' + c);
    return 0;
}

Where is the problem?


Branch "anticipation" in modern CPUs


I was recently thinking about branch prediction in modern CPUs. As far as I understand, branch prediction is necessary, because when executing instructions in a pipeline, we don't know the result of the conditional operation right before taking the branch.

Since I know that modern out-of-order CPUs can execute instructions in any order, as long as the data dependencies between them are met, my question is, can CPUs reorder instructions in such a way that the branch target is already known by the time the CPU needs to take the branch, thus can "anticipate" the branch direction, so it doesn't need to guess at all?

So can the CPU turn this:

do_some_work();
if(condition()) //evaluating here requires the cpu to guess the direction or stall
   do_this();
else
   do_that();

To this:

bool result = condition();
do_some_work(); //bunch of instructions that take longer than the pipeline length
if(result) //value of result is known, thus decision is always 100% correct
   do_this();
else
   do_that();

A particular and very common use case would be iterating over collections, where the exit condition is often loop-invariant(since we usually don't modify the collection while iterating over it).

My question is can modern generally CPUs do this, and if so, which particular CPU cores are known to have this feature?


Compiling 32 Bit Application on 64 Bit Linux


I'm trying to compile a program for 32 bit on a 64 bit Kali Linux operating system.

Here is my system information:

root@kali:~/Desktop# cat /proc/version
Linux version 3.18.0-kali3-amd64 (debian-kernel@lists.debian.org) (gcc version 4.7.2 (Debian 4.7.2-5) ) #1 SMP Debian 3.18.6-1~kali2 (2015-03-02)

When I try to compile my C project, it cannot find -lgcc:

root@kali:~/Desktop/Project# make
cc -o libor libor.c -fno-stack-protector -z execstack -m32 -lpthread
/usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-linux-gnu/4.7/libgcc.a when searching for -lgcc
/usr/bin/ld: cannot find -lgcc
/usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-linux-gnu/4.7/libgcc_s.so when searching for -lgcc_s
/usr/bin/ld: cannot find -lgcc_s
collect2: error: ld returned 1 exit status
make: *** [all] Error 1

Note that I'm using the -m32 flag to force compilation for 32 bit.

Like suggested elsewhere, the 32 bit libraries should be installed which I did using the following command:

sudo apt-get install libc6-dev-i386

This however only changed the error message to the one seen above. I lost the previous one however I guess it no longer matters.

Please note that existing answers didn't help me so this is not a duplicate.


Running .exe in cygwin opens windows console with MapViewOfFileEx error, how do I fix this?


I'm trying to run programs I've compiled with GCC. When I run them through cygwin, a windows terminal opens for a couple of miliseconds (or so) giving off the error:

 fatal error - MapViewOfFileEx shared 5'(0x66). win32 error 6. Terminating

It's followed by a stack trace. (this was the best shot, had to use video camera)

The error terminal

It doesn't seem to affect the programs but since it's a "fatal error" I suppose it would be good to fix. I tried googling the error, and found that multiple cygwin1.dll in the path shown when running the command

cygcheck -s

could be the cause, but I only found 1 cygwin1.dll.

The problem could have come from when I tried to open a cygwin-created executeable in windows and I read that I should copy the cygwin1.dll into my windows-folder but I simply deleted it after realizing that I needed several more files (libraries).


What kind of problems could generate defining a string type?


I've been using for a while the following line to create my own string type and make it easier to declare this kind of data:

typedef char *string;

Since I am trying to learn more about doing things the 'safe' way in C, I come to you guys with a question. In which way this could cause subsequent problems in my code, like memory leaks or lost pointers, etc...? It is clear for example that with this methodology there is no space reservation for a specific amount of characters.

Appreciate any hint!


C vs. Cython (why is cython faster)


I'm not going to copy/paste my entire program since it is a bit lengthy. But I'm simply curious as to what in gods name would cause a cython program to actual outperform a pure C version. I would really love some more speed, and I am confused as to how this is possible. Any ideas/suggestions for things to look into are welcome. Thanks!


qsort fails to sort large array of strings


I'm using qsort to sort an array of i strings of size 256, such as char *arr = malloc(i * 256) -- was actully done with reallocs inside a loop. Each string contains, among text, a number, which I use as the comparison element:

int                                                               
cmp(const void *a, const void *b)                                               
{                                                                               
  double atime = get_time((char*)a);                                            
  double btime = get_time((char*)b);                                            
  return (atime > btime) - (atime < btime);                                     
}

When i is small, it works. With a large i, it fails to sort the array correctly. get_time is working. I was using it with a custom heapsort implementation before, which worked flawlessly.

I added the following to cmp to check what was happening:

fprintf(stderr, "Comparing %f to %f, result: %d.\n", atime, btime, (atime > btime) - (atime < btime));

It seems that all comparisons are correct, but not all comparisons are being made. arr has several strings containing 1.something, however I couldn't find any comparison between numbers greater than 1 in the output. The call to qsort is as follows:

qsort((void*)arr, i-1, MAX_ROW_LEN, cmp);

It's the same parameters I used to pass to my heapsort function, but it doesn't work.

Complete code, and example file (fails to sort).


Mime type for time-stamped text in gstreamer subtitleoverlay element


According to the documentation, the subtitleoverlay element supports timestamped text. Is there a standard for times tamped text supported by this element? If yes, what is the mime type and the expected format?

I was able to render raw text read from a file on top of the video using the following pipeline:

gst-launch-0.10 videotestsrc ! \
    subtitleoverlay name=ovl ! \
    autovideosink \
    filesrc location=test.txt ! text/plain !  ovl.

But this just renders static text, not dynamic text based on the time stamps.


How can my C code find the symbol corresponding to an address at run-time (in Linux)?


Given a function or variable run-time address, my code needs to find out the name and, if it's a variable, type information of the symbol. Or at least provide enough information for later, off-line extraction of the name (and type info).

It is Linux code and it is assumed debug information is available.

I tried to look into the ELF file format, binutils and all but the subject is huge, so I was hoping somebody can help me narrow the scope.

I can see the following types of solutions:

  • find the range of the code/data segments of the modules currently loaded in memory - HOW TO DO THAT ?. Save the address's module and segment name and offset in it's segment. Off-line then use binutils to find the symbol in the module's debug info - again, HOW TO DO THAT?

  • use some API/system services I do not know of to find the symbol and info at run-time - HOW?

Thank you in advance.


How to check if string entered already exists in C


I am here with a doubt to create a function to check if a string entered by the user already exists in a struct.

I have the following struct to store cars data:

typedef struct
{
    char brand;
    char car_plate;
    char model;
} stCar;

For example when asked to enter the car_plate, i need a function to check if that car_plate already exists in the stCar struct because can not exist two cars with the same car_plate.

Someone can please help me?

Thanks.


How to fix sprintf error


The below code works just fine if I comment the sprintf line at the very bottom

int doStepOneAndTwo(){
FILE *fp, *source, *target, *fp1; 
   PROT prot;
   int i, j;
   int k, counter;
   int n_conf;
   int number_of_dir;
   int number_of_line;
   char sbuff[256];
   char str[256];
   char str1[256];
   int ch;
   const char *a[5];

   number_of_line = 140;
   number_of_dir = ceil( number_of_line /30) + 1;
   a[0] = "submit.sh";
   a[1] = FN_RUNPRM;   // run.prm
   a[2] = env.rename_rules; // name.txt
   a[3] = env.inpdb; // prot.pdb
   a[4] = STEP2_OUT; // step2_out.pdb

   for (i=1; i<=number_of_dir; i++)
    {

      sprintf(str,"_%d", i);
      mkdir(str,"0755"); // Create temporary directories

      for (j=0;j<5;j++)
      {
          sprintf(str,"%s", a[j]);
          source = fopen(str, "r");
          if( source == NULL ) 
            {
                printf("Error in doStepOneAndTwo, can't open file source \n");
                return USERERR;
            }
          sprintf(str,"_%d/%s", i, a[j]);
          target = fopen(str, "w");
          if( target == NULL ) 
            {
                fclose(source);
                printf("Error in doStepOneAndTwo, can't open file target %s \n",str);
                return USERERR;
            }


          while( (ch = fgetc(source)) != EOF) {
              fputc(ch, target);
          }

          //if(k!=1){printf("fuck me");}else{printf("fuck you \n");}
          //k++;

      }

    }
    fclose(source);
    fclose(target);

for (k=1; k<2; k++)
    {
        printf("Yes %d \n",k);

        sprintf(str1,"_%d/run.prm",k); // If I comment this line everything works just fine 
        //chdir("_1");
        fp1=fopen(FN_RUNPRM, "r");
    }

return 0;

}

The error I get is "Error in doStepOneAndTwo, can't open file target _1/submit.sh" . Basically, the target file is NULL. I'm new to c and don't know what I'm doing wrong.


How to read text file in C?


I'm trying to read a txt file containing strings of 1s and 0s and print it out in the manner below. I tried my code a couple of months ago and it worked fine in reading the text file. Now when I tried it, it outputs something really strange. Also I tried changing the directory of the file to a non-existant file but it still outputs the same thing when it should've quit the program immediately. Please help!

The content of txt file:-

10000001
01110111
01111111
01111010
01111010
01110111

Expected output:-

data_in<=24'b10000001;
#10000;

Real output:-

data_in<=24'b(some weird symbol that changes everytime I recompile);
#10000;

My code:-

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

int main(int argc, char *argv[])
{
int i,j;
j = 0;
char words [50];
FILE* fp;
fp = fopen(argv[1], "r");

if(fp==NULL)
{

printf("Can't open file\n");
}


while(feof(fp)==0)
{
fscanf(fp,"%s", words);
printf("data_in<=24'b%s\n", words);
printf("#10000\n");


}

fclose(fp);
system("PAUSE");
return 0;
}

The input argument is the following:-

"C:\Users\Beanz\Documents\MATLAB\football frame\frame1.txt"


Program crashes. Deciphering the error message


I just released a multi-language image processing software as an ImageJ plugin. It has components written in Jython, C and Java. The C programs are called through the JNA. The software runs perfectly on my Macbook pro OSX Yosemite (64-bit). I sent the program to a long distance colleague and he tried running it on his computer (Macbook Air) and it crashed violently. The problem appears to be in a multithreaded C component of the program. If I were to guess , it probably had something to do with deallocating an already freed pointer and therefore destabilizing the whole program. I checked and sent him a more safer version but he says the problem still persists. Here is the link to the relevant code.

Here is part of the error message:

Process:               JavaApplicationStub [12285]
Path:                  /Applications/ImageJ/http://ift.tt/1dvn2t9
Identifier:            gov.nih.info.rsb.ImageJ
Version:               10.2
Code Type:             X86-64 (Native)
Parent Process:        ??? [1]
Responsible:           JavaApplicationStub [12285]
User ID:               501

Date/Time:             2015-06-30 13:22:36.186 -0400
OS Version:            Mac OS X 10.10.3 (14D136)
Report Version:        11
Anonymous UUID:        AC745C9B-736D-93B0-9896-25C03329CC79

Sleep/Wake UUID:       1D9C670A-85E4-4A80-9CA5-B73C5E6792B9

Time Awake Since Boot: 110000 seconds
Time Since Wake:       740 seconds

Crashed Thread:        22  Java: Run$_CANDLEMacro$

Exception Type:        EXC_BAD_ACCESS (SIGSEGV)
Exception Codes:       KERN_INVALID_ADDRESS at 0x0000000000000800

VM Regions Near 0x800:
--> 
   __TEXT                 0000000100000000-0000000100001000 [    4K] r-x/rwx SM=COW /Applications/ImageJ/http://ift.tt/1dvn2t9

Application Specific Information:
Java information:
Exception type: Bus Error (0xa) at pc=100407080

Java VM: Java HotSpot(TM) 64-Bit Server VM (20.65-b04-466.1 mixed mode macosx-amd64)

.
.
.

VM state:not at safepoint (normal execution)
VM Mutex/Monitor currently owned by a thread: None

Heap
par new generation   total 49536K, used 905K [73f600000, 742bc0000, 744930000)
 eden space 44032K,   2% used [73f600000, 73f6dfa30, 742100000)
 from space 5504K,   0% used [742660000, 742662ca8, 742bc0000)
 to   space 5504K,   0% used [742100000, 742100000, 742660000)
concurrent mark-sweep generation total 456744K, used 274044K [744930000, 76073a000, 7fae00000)
concurrent-mark-sweep perm gen total 61252K, used 36701K [7fae00000, 7fe9d1000, 800000000)

Code Cache  [107001000, 107272000, 10a001000)
total_blobs=981 nmethods=394 adapters=549 free_code_cache=48669056 largest_free_block=6592

Virtual Machine Arguments:
JVM Args: -Xbootclasspath/a:/System/Library/PrivateFrameworks/JavaApplicationLauncher.framework/Resources/LauncherSupport.jar -Xms256m -Xmx3000m -Dapple.awt.Antialiasing=false -Dcom.apple.macos.useScreenMenuBar=false -Dcom.apple.hwaccel=false -Dapple.awt.brushMetalLook=false -Dcom.apple.mrj.application.live-resize=true -Dcom.apple.smallTabs=true -Dcom.apple.mrj.application.growbox.intrudes=false 
Java Command: <unknown>
Launcher Type: generic
Physical Memory: Page Size = 4k, Total = 8192M, Free = 475M


Thread 0:: Dispatch queue: com.apple.main-thread
0   libsystem_kernel.dylib          0x00007fff88e694de mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff88e6864f mach_msg + 55
2   com.apple.CoreFoundation        0x00007fff89041eb4 __CFRunLoopServiceMachPort + 212
3   com.apple.CoreFoundation        0x00007fff8904137b __CFRunLoopRun + 1371
4   com.apple.CoreFoundation        0x00007fff89040bd8 CFRunLoopRunSpecific + 296
5   com.apple.HIToolbox             0x00007fff88b6956f RunCurrentEventLoopInMode + 235
6   com.apple.HIToolbox             0x00007fff88b692ea ReceiveNextEventCommon + 431
7   com.apple.HIToolbox             0x00007fff88b6912b _BlockUntilNextEventMatchingListInModeWithFilter + 71
8   com.apple.AppKit                0x00007fff896a69bb _DPSNextEvent + 978
9   com.apple.AppKit                0x00007fff896a5f68 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 346
10  libawt.jnilib                   0x000000011222b86f -[NSApplicationAWT nextEventMatchingMask:untilDate:inMode:dequeue:] + 124
11  com.apple.AppKit                0x00007fff8969bbf3 -[NSApplication run] + 594
12  libawt.jnilib                   0x0000000112229f20 +[AWTStarter startAWT:] + 1495
13  libawt.jnilib                   0x000000011222989a -[CPerformer perform] + 93
14  com.apple.Foundation            0x00007fff91077d00 __NSThreadPerformPerform + 293
15  com.apple.CoreFoundation        0x00007fff8904fa01 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
16  com.apple.CoreFoundation        0x00007fff89041b8d __CFRunLoopDoSources0 + 269
17  com.apple.CoreFoundation        0x00007fff890411bf __CFRunLoopRun + 927
18  com.apple.CoreFoundation        0x00007fff89040bd8 CFRunLoopRunSpecific + 296
19  com.apple.JavaApplicationLauncher   0x00000001000060e4 startupJava(LauncherArgsStruct*) + 245
20  com.apple.JavaApplicationLauncher   0x0000000100008bc9 launchJavaApplicationWithJVMInfo + 1457
21  gov.nih.info.rsb.ImageJ         0x0000000100000b98 0x100000000 + 2968

Thread 1:: Dispatch queue: com.apple.libdispatch-manager
0   libsystem_kernel.dylib          0x00007fff88e6f232 kevent64 + 10
1   libdispatch.dylib               0x00007fff8a3b2a6a _dispatch_mgr_thread + 52

Thread 2:
0   libsystem_kernel.dylib          0x00007fff88e694de mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff88e6864f mach_msg + 55
2   libclient64.dylib               0x00000001048c26a3 0x104803000 + 784035
3   libclient64.dylib               0x0000000104816600 0x104803000 + 79360
4   libclient64.dylib               0x00000001048c264e 0x104803000 + 783950
5   libclient64.dylib               0x00000001048c255d 0x104803000 + 783709
6   libclient64.dylib               0x000000010481618e 0x104803000 + 78222
7   libclient64.dylib               0x00000001048bd2a6 0x104803000 + 762534
8   libclient64.dylib               0x00000001048bce07 0x104803000 + 761351
9   com.apple.JavaApplicationLauncher   0x0000000100007da1 startJavaApplication + 7257
10  com.apple.JavaApplicationLauncher   0x0000000100006110 java_main_stub(void*) + 9
11  libsystem_pthread.dylib         0x00007fff9152b268 _pthread_body + 131
12  libsystem_pthread.dylib         0x00007fff9152b1e5 _pthread_start + 176
13  libsystem_pthread.dylib         0x00007fff9152941d thread_start + 13

Thread 3:: Java: Exception Handler Thread
0   libsystem_kernel.dylib          0x00007fff88e694de mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff88e6864f mach_msg + 55
2   libsystem_kernel.dylib          0x00007fff88e68f60 mach_msg_server + 468
3   libclient64.dylib               0x0000000104816f45 0x104803000 + 81733
4   libclient64.dylib               0x0000000104816f09 0x104803000 + 81673
5   libclient64.dylib               0x000000010481607a 0x104803000 + 77946
6   libsystem_pthread.dylib         0x00007fff9152b268 _pthread_body + 131
7   libsystem_pthread.dylib         0x00007fff9152b1e5 _pthread_start + 176
8   libsystem_pthread.dylib         0x00007fff9152941d thread_start + 13

.
.
.

Thread 12:: Java: Surrogate Locker Thread (Concurrent GC)
0   libsystem_kernel.dylib          0x00007fff88e694de mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff88e6864f mach_msg + 55
2   libclient64.dylib               0x00000001048c26a3 0x104803000 + 784035
3   libclient64.dylib               0x0000000104816600 0x104803000 + 79360
4   libclient64.dylib               0x00000001048c264e 0x104803000 + 783950
5   libclient64.dylib               0x00000001048c255d 0x104803000 + 783709
6   libclient64.dylib               0x0000000104816176 0x104803000 + 78198
7   libclient64.dylib               0x0000000104aed18b 0x104803000 + 3056011
8   libclient64.dylib               0x00000001048a5bbe 0x104803000 + 666558
9   libclient64.dylib               0x00000001048a59cf 0x104803000 + 666063
10  libclient64.dylib               0x000000010481607a 0x104803000 + 77946
11  libsystem_pthread.dylib         0x00007fff9152b268 _pthread_body + 131
12  libsystem_pthread.dylib         0x00007fff9152b1e5 _pthread_start + 176
13  libsystem_pthread.dylib         0x00007fff9152941d thread_start + 13

Thread 13:: Java: Signal Dispatcher
0   libsystem_kernel.dylib          0x00007fff88e6951a semaphore_wait_trap + 10
1   libclient64.dylib               0x00000001048b6463 0x104803000 + 734307
2   libclient64.dylib               0x00000001048b5f30 0x104803000 + 732976
3   libclient64.dylib               0x00000001048a5bbe 0x104803000 + 666558
4   libclient64.dylib               0x00000001048a59cf 0x104803000 + 666063
5   libclient64.dylib               0x000000010481607a 0x104803000 + 77946
6   libsystem_pthread.dylib         0x00007fff9152b268 _pthread_body + 131
7   libsystem_pthread.dylib         0x00007fff9152b1e5 _pthread_start + 176
8   libsystem_pthread.dylib         0x00007fff9152941d thread_start + 13

Thread 14:: Java: C2 CompilerThread0
0   libsystem_kernel.dylib          0x00007fff88e694de mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff88e6864f mach_msg + 55
2   libclient64.dylib               0x00000001048c26a3 0x104803000 + 784035
3   libclient64.dylib               0x0000000104816600 0x104803000 + 79360
4   libclient64.dylib               0x00000001048c264e 0x104803000 + 783950
5   libclient64.dylib               0x00000001048c255d 0x104803000 + 783709
6   libclient64.dylib               0x0000000104816176 0x104803000 + 78198
7   libclient64.dylib               0x00000001048bc4c5 0x104803000 + 758981
8   libclient64.dylib               0x00000001048b72af 0x104803000 + 737967
9   libclient64.dylib               0x00000001048a5bbe 0x104803000 + 666558
10  libclient64.dylib               0x00000001048a59cf 0x104803000 + 666063
11  libclient64.dylib               0x000000010481607a 0x104803000 + 77946
12  libsystem_pthread.dylib         0x00007fff9152b268 _pthread_body + 131
13  libsystem_pthread.dylib         0x00007fff9152b1e5 _pthread_start + 176
14  libsystem_pthread.dylib         0x00007fff9152941d thread_start + 13

Thread 15:: Java: C2 CompilerThread1
0   libsystem_kernel.dylib          0x00007fff88e694de mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff88e6864f mach_msg + 55
2   libclient64.dylib               0x00000001048c26a3 0x104803000 + 784035
3   libclient64.dylib               0x0000000104816600 0x104803000 + 79360
4   libclient64.dylib               0x00000001048c264e 0x104803000 + 783950
5   libclient64.dylib               0x00000001048c255d 0x104803000 + 783709
6   libclient64.dylib               0x0000000104816176 0x104803000 + 78198
7   libclient64.dylib               0x00000001048bc4c5 0x104803000 + 758981
8   libclient64.dylib               0x00000001048b72af 0x104803000 + 737967
9   libclient64.dylib               0x00000001048a5bbe 0x104803000 + 666558
10  libclient64.dylib               0x00000001048a59cf 0x104803000 + 666063
11  libclient64.dylib               0x000000010481607a 0x104803000 + 77946
12  libsystem_pthread.dylib         0x00007fff9152b268 _pthread_body + 131
13  libsystem_pthread.dylib         0x00007fff9152b1e5 _pthread_start + 176
14  libsystem_pthread.dylib         0x00007fff9152941d thread_start + 13

Thread 16:: Java: Low Memory Detector
0   libsystem_kernel.dylib          0x00007fff88e694de mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff88e6864f mach_msg + 55
2   libclient64.dylib               0x00000001048c26a3 0x104803000 + 784035
3   libclient64.dylib               0x0000000104816600 0x104803000 + 79360
4   libclient64.dylib               0x00000001048c264e 0x104803000 + 783950
5   libclient64.dylib               0x00000001048c255d 0x104803000 + 783709
6   libclient64.dylib               0x000000010481620f 0x104803000 + 78351
7   libclient64.dylib               0x00000001048b9c9e 0x104803000 + 748702
8   libclient64.dylib               0x00000001048a5bbe 0x104803000 + 666558
9   libclient64.dylib               0x00000001048a59cf 0x104803000 + 666063
10  libclient64.dylib               0x000000010481607a 0x104803000 + 77946
11  libsystem_pthread.dylib         0x00007fff9152b268 _pthread_body + 131
12  libsystem_pthread.dylib         0x00007fff9152b1e5 _pthread_start + 176
13  libsystem_pthread.dylib         0x00007fff9152941d thread_start + 13

Thread 17:: Java: VM Periodic Task Thread
0   libsystem_kernel.dylib          0x00007fff88e694de mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff88e6864f mach_msg + 55
2   libclient64.dylib               0x00000001048c2735 0x104803000 + 784181
3   libclient64.dylib               0x00000001048d7f86 0x104803000 + 872326
4   libclient64.dylib               0x00000001048bb880 0x104803000 + 755840
5   libclient64.dylib               0x000000010481607a 0x104803000 + 77946
6   libsystem_pthread.dylib         0x00007fff9152b268 _pthread_body + 131
7   libsystem_pthread.dylib         0x00007fff9152b1e5 _pthread_start + 176
8   libsystem_pthread.dylib         0x00007fff9152941d thread_start + 13

Thread 18:: Java: AWT-Shutdown
0   libsystem_kernel.dylib          0x00007fff88e694de mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff88e6864f mach_msg + 55
2   libclient64.dylib               0x00000001048c26a3 0x104803000 + 784035
3   libclient64.dylib               0x0000000104816600 0x104803000 + 79360
4   libclient64.dylib               0x00000001048d8377 0x104803000 + 873335
5   libclient64.dylib               0x00000001048d80c6 0x104803000 + 872646
6   libclient64.dylib               0x00000001048a6303 JVM_MonitorWait + 156
7   libjvmlinkage.dylib             0x00000001000bbb0b JVM_MonitorWait + 59
8   ???                             0x00000001070bdd08 0 + 4413185288

Thread 19:
0   libsystem_kernel.dylib          0x00007fff88e694de mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff88e6864f mach_msg + 55
2   com.apple.CoreFoundation        0x00007fff89041eb4 __CFRunLoopServiceMachPort + 212
3   com.apple.CoreFoundation        0x00007fff8904137b __CFRunLoopRun + 1371
4   com.apple.CoreFoundation        0x00007fff89040bd8 CFRunLoopRunSpecific + 296
5   com.apple.AppKit                0x00007fff8976e66b _NSEventThread + 137
6   libsystem_pthread.dylib         0x00007fff9152b268 _pthread_body + 131
7   libsystem_pthread.dylib         0x00007fff9152b1e5 _pthread_start + 176
8   libsystem_pthread.dylib         0x00007fff9152941d thread_start + 13

Thread 20:: Java: Java2D Disposer
0   libsystem_kernel.dylib          0x00007fff88e694de mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff88e6864f mach_msg + 55
2   libclient64.dylib               0x00000001048c26a3 0x104803000 + 784035
3   libclient64.dylib               0x0000000104816600 0x104803000 + 79360
4   libclient64.dylib               0x00000001048d8377 0x104803000 + 873335
5   libclient64.dylib               0x00000001048d80c6 0x104803000 + 872646
6   libclient64.dylib               0x00000001048a6303 JVM_MonitorWait + 156
7   libjvmlinkage.dylib             0x00000001000bbb0b JVM_MonitorWait + 59
8   ???                             0x00000001070bdd08 0 + 4413185288
9   ???                             0x000000010700685a 0 + 4412434522
10  ???                             0x00000001070069b3 0 + 4412434867
11  ???                             0x00000001070069b3 0 + 4412434867
12  ???                             0x0000000107006d34 0 + 4412435764
13  ???                             0x0000000107001438 0 + 4412412984
14  libclient64.dylib               0x0000000104899b54 0x104803000 + 617300
15  libclient64.dylib               0x00000001048a5e8e 0x104803000 + 667278
16  libclient64.dylib               0x00000001048a5d80 0x104803000 + 667008
17  libclient64.dylib               0x00000001048a5d20 0x104803000 + 666912
18  libclient64.dylib               0x00000001048a5bbe 0x104803000 + 666558
19  libclient64.dylib               0x00000001048a59cf 0x104803000 + 666063
20  libclient64.dylib               0x000000010481607a 0x104803000 + 77946
21  libsystem_pthread.dylib         0x00007fff9152b268 _pthread_body + 131
22  libsystem_pthread.dylib         0x00007fff9152b1e5 _pthread_start + 176
23  libsystem_pthread.dylib         0x00007fff9152941d thread_start + 13

Thread 21:: Java: AWT-EventQueue-0
0   libsystem_kernel.dylib          0x00007fff88e694de mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff88e6864f mach_msg + 55
2   libclient64.dylib               0x00000001048c26a3 0x104803000 + 784035
3   libclient64.dylib               0x0000000104816600 0x104803000 + 79360
4   libclient64.dylib               0x00000001048d8377 0x104803000 + 873335
5   libclient64.dylib               0x00000001048d80c6 0x104803000 + 872646
6   libclient64.dylib               0x00000001048a6303 JVM_MonitorWait + 156
7   libjvmlinkage.dylib             0x00000001000bbb0b JVM_MonitorWait + 59
8   ???                             0x00000001070bdd08 0 + 4413185288
9   ???                             0x00000001070b1d7c 0 + 4413136252

Thread 22 Crashed:: Java: Run$_CANDLEMacro$
0   libONLM_Mod.dylib               0x0000000100407080 ONLM + 224
1   jna1934359639328178547.tmp      0x00000001005ab94c ffi_call_unix64 + 76
2   jna1934359639328178547.tmp      0x00000001005ab456 ffi_call + 630
3   jna1934359639328178547.tmp      0x00000001005a22f5 Java_com_sun_jna_Native_ffi_1prep_1cif + 1621
4   jna1934359639328178547.tmp      0x00000001005a2772 Java_com_sun_jna_Native_invokeVoid + 34
5   ???                             0x0000000107011eee 0 + 4412481262
6   ???                             0x000000010700685a 0 + 4412434522
7   ???                             0x00000001070069b3 0 + 4412434867
8   ???                             0x00000001070069b3 0 + 4412434867
9   ???                             0x0000000107006e8d 0 + 4412436109
10  ???                             0x0000000107006d34 0 + 4412435764
11  ???                             0x0000000107001438 0 + 4412412984
12  libclient64.dylib               0x0000000104899b54 0x104803000 + 617300
13  libclient64.dylib               0x0000000104899918 0x104803000 + 616728
14  libclient64.dylib               0x00000001048b1254 0x104803000 + 713300
15  libclient64.dylib               0x00000001048b246e 0x104803000 + 717934
16  libclient64.dylib               0x00000001048b222e JVM_InvokeMethod + 358
17  libjvmlinkage.dylib             0x00000001000bfd7e JVM_InvokeMethod + 78
18  ???                             0x0000000107011eee 0 + 4412481262
19  ???                             0x00000001070069b3 0 + 4412434867
20  ???                             0x00000001070069b3 0 + 4412434867
21  ???                             0x0000000107006e8d 0 + 4412436109
22  ???                             0x00000001070069b3 0 + 4412434867
23  ???                             0x00000001070069b3 0 + 4412434867
24  ???                             0x00000001070069b3 0 + 4412434867
25  ???                             0x00000001070069b3 0 + 4412434867
26  ???                             0x00000001070069b3 0 + 4412434867
27  ???                             0x00000001070069b3 0 + 4412434867
28  ???                             0x00000001070069b3 0 + 4412434867
29  ???                             0x00000001070069b3 0 + 4412434867
30  ???                             0x00000001070069b3 0 + 4412434867
31  ???                             0x00000001070069b3 0 + 4412434867
32  ???                             0x000000010700685a 0 + 4412434522
33  ???                             0x000000010700685a 0 + 4412434522
34  ???                             0x000000010700685a 0 + 4412434522
35  ???                             0x00000001070069b3 0 + 4412434867
36  ???                             0x00000001070069b3 0 + 4412434867
37  ???                             0x00000001070069b3 0 + 4412434867
38  ???                             0x00000001070069b3 0 + 4412434867
39  ???                             0x0000000107006d34 0 + 4412435764
40  ???                             0x00000001070069b3 0 + 4412434867
41  ???                             0x000000010700685a 0 + 4412434522
42  ???                             0x0000000107006d34 0 + 4412435764
43  ???                             0x0000000107001438 0 + 4412412984
44  libclient64.dylib               0x0000000104899b54 0x104803000 + 617300
45  libclient64.dylib               0x00000001048a5e8e 0x104803000 + 667278
46  libclient64.dylib               0x00000001048a5d80 0x104803000 + 667008
47  libclient64.dylib               0x00000001048a5d20 0x104803000 + 666912
48  libclient64.dylib               0x00000001048a5bbe 0x104803000 + 666558
49  libclient64.dylib               0x00000001048a59cf 0x104803000 + 666063
50  libclient64.dylib               0x000000010481607a 0x104803000 + 77946
51  libsystem_pthread.dylib         0x00007fff9152b268 _pthread_body + 131
52  libsystem_pthread.dylib         0x00007fff9152b1e5 _pthread_start + 176
53  libsystem_pthread.dylib         0x00007fff9152941d thread_start + 13

Thread 23:: Java: org.python.google.common.base.internal.Finalizer
0   libsystem_kernel.dylib          0x00007fff88e694de mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff88e6864f mach_msg + 55
2   libclient64.dylib               0x00000001048c26a3 0x104803000 + 784035
3   libclient64.dylib               0x0000000104816600 0x104803000 + 79360
4   libclient64.dylib               0x00000001048d8377 0x104803000 + 873335
5   libclient64.dylib               0x00000001048d80c6 0x104803000 + 872646
6   libclient64.dylib               0x00000001048a6303 JVM_MonitorWait + 156
7   libjvmlinkage.dylib             0x00000001000bbb0b JVM_MonitorWait + 59
8   ???                             0x00000001070bdd08 0 + 4413185288
9   ???                             0x000000010700685a 0 + 4412434522
10  ???                             0x00000001070069b3 0 + 4412434867
11  ???                             0x00000001070069b3 0 + 4412434867
12  ???                             0x0000000107001438 0 + 4412412984
13  libclient64.dylib               0x0000000104899b54 0x104803000 + 617300
14  libclient64.dylib               0x00000001048a5e8e 0x104803000 + 667278
15  libclient64.dylib               0x00000001048a5d80 0x104803000 + 667008
16  libclient64.dylib               0x00000001048a5d20 0x104803000 + 666912
17  libclient64.dylib               0x00000001048a5bbe 0x104803000 + 666558
18  libclient64.dylib               0x00000001048a59cf 0x104803000 + 666063
19  libclient64.dylib               0x000000010481607a 0x104803000 + 77946
20  libsystem_pthread.dylib         0x00007fff9152b268 _pthread_body + 131
21  libsystem_pthread.dylib         0x00007fff9152b1e5 _pthread_start + 176
22  libsystem_pthread.dylib         0x00007fff9152941d thread_start + 13

Thread 24:: com.apple.CoreAnimation.render-server
0   libsystem_kernel.dylib          0x00007fff88e694de mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff88e6864f mach_msg + 55
2   com.apple.QuartzCore            0x00007fff9416b04f CA::Render::Server::server_thread(void*) + 198
3   com.apple.QuartzCore            0x00007fff9416af82 thread_fun + 25
4   libsystem_pthread.dylib         0x00007fff9152b268 _pthread_body + 131
5   libsystem_pthread.dylib         0x00007fff9152b1e5 _pthread_start + 176
6   libsystem_pthread.dylib         0x00007fff9152941d thread_start + 13

Thread 25:
0   libsystem_kernel.dylib          0x00007fff88e6e94a __workq_kernreturn + 10
1   libsystem_pthread.dylib         0x00007fff9152940d start_wqthread + 13

Thread 22 crashed with X86 Thread State (64-bit):
 rax: 0x0000000139399000  rbx: 0x0000000000000200  rcx: 0x0000000000000800  rdx: 0x0000000000000008
 rdi: 0x0000000100031280  rsi: 0x00000000000000a9  rbp: 0x00000001174ee850  rsp: 0x00000001174ee720
  r8: 0x0000000003000001   r9: 0x0000000000000003  r10: 0x0000000000000000  r11: 0x0000000000000246
 r12: 0x0000000000000008  r13: 0x000000000000000a  r14: 0xa900b50506ac8350  r15: 0x00000001174ee9f0
 rip: 0x0000000100407080  rfl: 0x0000000000010202  cr2: 0x0000000000000800

Logical CPU:     3
Error Code:      0x00000006
Trap Number:     14

The relevant machine:

Model: MacBookAir6,1, BootROM MBA61.0099.B18, 2 processors, Intel Core i7, 1.7 GHz, 8 GB, SMC 2.12f143
Graphics: Intel HD Graphics 5000, Intel HD Graphics 5000, Built-In



#include <stdio.h>

int main() {
    int x=5;
    printf("%d", printf("%d %d",x,x));
}

how is the output 5 53 can sum1 explain ? I tried myself and i think the ans should be 5 5 2


const and typedef of arrays in C


In C, it's possible to typedef an array, using this construction :

typedef int table_t[N];

Here, table_t is now defined as an array of N int. Any variable declared such as table_t t; will now behave as a normal array of int.

The point of such construction is to be used as an argument type in a function, such as :

int doSomething(table_t t);

A relatively equivalent function prototype could have been :

int doSomething(int* t);

The merit of the first construction is that it enforces N as the size of the table. In many circumstances, it's safer to enforce this property, rather than relying on the programmer to properly figure out this condition.

Now it's all good, except that, in order to guarantee that the content of table will not be modified, it's necessary to use the const qualifier.

The following statement is relatively simple to understand :

int doSomething(const int* t);

Now, doSomething guarantee that it will not modify the content of the table passed as a pointer. Now, what about this almost equivalent construction ? :

int doSomething(const table_t t);

What is const here ? the content of the table, or the pointer to the table ? If it's the pointer which is const, is there another way (C90 compatible) to retain the ability to define the size of the table and to tell that its content will be const ?

Note that it's also necessary sometimes to modify the content of the table, so the const property cannot be embedded into the typedef definition.

[Edit] Thanks for the excellent answers received so far. To summarize :

  • The initial assumption of typedef enforcing size N was completely wrong. It basically behaves the same as a normal pointer.
  • The const property will also behave the same as if it was a pointer (in stark contrast with a typedef to a pointer type, as underlined by @random below)
  • To enforce a size (which was not the initial question, but end up being quite important now...), see Jonathan's answer

Destroying pthread mutex/rwlock in signal handler


How to correctly destroy pthread mutex or rwlock in signal handler? For example - in the code below i has main thread and 3 another threads. All threads do some tasks in infinity loop on some array, using mutexes and locks. Because main thread is also doing some task, the only way to exit from program - using signal handler. But in this way i can't destroy my mutex/rwlock object, because there's no guarantee that object is unlocked. And if I'll try to unlock it, of course one of thread will lock it again. And when i'm trying to launch my program again, that print corrupted result. So how can i solve this problem? There is example of my code with rwlocks:

#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <ctype.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <signal.h>

#include <stdlib.h>

#include "thread_data.h"
#include "exchange_types.h"

pthread_rwlock_t rwlock;

unsigned int main_time   = 500000;
unsigned int shift_time  = 1000000;
unsigned int mirror_time = 2000000;
unsigned int count_time  = 4000000;

void signal_handler(int signo) {

    // Destroying locked lock or mutex is UB
    pthread_rwlock_destroy(&rwlock);
    exit(1);

}

void* shift_letter_case_async( void* array ) {

    while(1) {

        if( pthread_rwlock_rdlock(&rwlock) < 0 )
            handle_error("rdlock[shift]");

        carray_t* arr = (carray_t*) array;
        shift_letter_case( arr->array, arr->size );

        if( pthread_rwlock_unlock(&rwlock) < 0 )
            handle_error("unlock[shift]");

        usleep(shift_time);

    }

    return NULL;

}

void* mirror_array_async( void* array ) {

    while(1) {

        if( pthread_rwlock_rdlock(&rwlock) < 0 )
            handle_error("rdlock[mirror]");

        carray_t* arr = (carray_t*) array;
        mirror_array( arr->array, arr->size );

        if( pthread_rwlock_unlock(&rwlock) < 0 )
            handle_error("unlock[mirror]");

        usleep(mirror_time);

    }

    return NULL;

}

void* count_async( void* array ) {

    while(1) {

        if( pthread_rwlock_wrlock(&rwlock) < 0 )
            handle_error("wrlock[count]");

        carray_t* arr = (carray_t*) array;
        count_upper_letters( arr->array, arr->size );

        if( pthread_rwlock_unlock(&rwlock) < 0 )
            handle_error("unlock[count]");

        usleep(count_time);

    }

    return NULL;

}

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

    /* Common data */
    char letters[ 'z' - 'a' + 1 ];
    size_t letter_len;
    carray_t transferer;
    /* pthread data */
    pthread_t threads[3];

    /* Initializing array */
    letter_len = sizeof(letters);
    for( int i = 0; i < letter_len; i++ )       
        letters[i] = 'a' + i;

    transferer.array = letters;
    transferer.size = letter_len;

    /* Initializing signal handlers */
    if ( signal(SIGINT, signal_handler) == SIG_ERR )
        handle_error("signal[SIGINT]");
    if ( signal(SIGTERM, signal_handler) == SIG_ERR )
        handle_error("signal[SIGTERM]");

    /* Initializing locks */
    if( pthread_rwlock_init(&rwlock, NULL) < 0 )
        handle_error("pthread_rwlock_init");

    /* Initializing threads */
    if( pthread_create( &threads[0], NULL, shift_letter_case_async, &transferer ) != 0 )
        handle_error("phtread_create[shift_letter_case]");

    if( pthread_create( &threads[1], NULL, mirror_array_async, &transferer ) != 0 )
        handle_error("phtread_create[mirror_array]");

    if( pthread_create( &threads[2], NULL, count_async, &transferer ) != 0 )
        handle_error("phtread_create[count]");

    while(1) {      

        if( pthread_rwlock_wrlock(&rwlock) < 0 )
            handle_error("wrlock[main]");

        print_array(letters, letter_len);

        if( pthread_rwlock_unlock(&rwlock) < 0 )
            handle_error("unlock[main]");

        usleep(main_time);


    }

    return 0;

}


Is it possible to generate random floating point numbers including subnormals, with rand() of math.h?


I would like to generate floating point numbers that include subnormal floating point numbers. Can we use the routine rand() of math.h to achieve this? The programming language should be C99.


Implementing Rosseta Code FFT into VBA Excel


I attempted to implement the FFT Rosetta Code into VBA excel. I was unable to reconstruct the same output data exactly as written in the Rosetta Code. At first I thought it was type conversion mismatch, but scaling the input values by 1.1 scaled the output values by 1.1 as well. The only aspect of my code that I think could be in question is how I implemented the referenced arrays in code versus what Rosetta writes. I discovered Rosetta shifts the addresses of the arrays by writing out + step and buf + step in its odd recursion calls. I am unaware of a similar construction in VBA, so I simply passed an additional recursion parameter shift, which keeps track of the shifting of addresses as its passed into the next recursion call.

What is wrong with my shift implementation or is it something else?

Rosetta claims its FFT is memory in place, however they make an extra copy of the data and store it into out[]. I would appreciate an explanation of why this is so.

FFT Rosetta Code in C

void _fft(cplx buf[], cplx out[], int n, int step)
{
    if (step < n) {
        _fft(out, buf, n, step * 2);
        _fft(out + step, buf + step, n, step * 2);

        for (int i = 0; i < n; i += 2 * step) {
            cplx t = cexp(-I * PI * i / n) * out[i + step];
            buf[i / 2]     = out[i] + t;
            buf[(i + n)/2] = out[i] - t;
        }
    }
}

void fft(cplx buf[], int n)
{
    cplx out[n];
    for (int i = 0; i < n; i++) out[i] = buf[i];

    _fft(buf, out, n, 1);
}

My attempted FFT in VBA

Private Sub rec_fft(ByRef buf, ByRef out, ByVal n, ByVal step, ByVal shift)
If step < n Then
    Dim ii As Long
    Dim pi As Double
    pi = 3.14159265358979 + 3.23846264338328E-15
    Dim c1(1 To 2) As Long
    Dim c2(1 To 2) As Double
    Call rec_fft(out, buf, n, step * 2, shift)
    Call rec_fft(out, buf, n, step * 2, shift + step)
    For i = 1 To n / (2 * step)
        ii = 2 * step * (i - 1)    
        c1(1) = Cos(-1 * pi * CDbl(ii) / CDbl(n))
        c1(2) = Sin(-1 * pi * CDbl(ii) / CDbl(n))
        c2(1) = c1(1) * out(shift + 1 + ii + step, 1) - c1(2) * out(shift + 1 + ii + step, 2)
        c2(2) = c1(1) * out(shift + 1 + ii + step, 2) + c1(2) * out(shift + 1 + ii + step, 1)
        buf(shift + 1 + ii / 2, 1) = out(shift + 1 + ii, 1) + c2(1)
        buf(shift + 1 + ii / 2, 2) = out(shift + 1 + ii, 2) + c2(2)
        buf(shift + 1 + (ii + n) / 2, 1) = out(shift + 1 + ii, 1) - c2(1)
        buf(shift + 1 + (ii + n) / 2, 2) = out(shift + 1 + ii, 2) - c2(2)
    Next i
End If

End Sub

Private Sub fft(ByRef buf, ByVal n)
    Dim out() As Double
    ReDim out(1 To n, 1 To 2)
    For i = 1 To n
        out(i, 1) = buf(i, 1)
        out(i, 2) = buf(i, 2)
    Next i
    Call rec_fft(buf, out, n, 1, 0)
End Sub

Output Comparison

Input Data: 1 1 1 1 0 0 0 0 
Rosetta FFT : 4 (1, -2.41421) 0 (1, -0.414214) 0 (1, 0.414214) 0 (1, 2.41421)
My FFt : 4 (1, -3) 0 (1, -1) 0 (1, 1) 0 (1, 3)


Can .h files have classes and still work in C?


Is it possible for .h files to be used in c even if they have classes? If so, how is this done?

Thanks!


How to convert character string in microseconds to struct tm in C?


I have a string that contains microseconds since the epoch. How could I convert it to a time structure?

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

int main ()
{
    struct tm tm; 
    char buffer [80];
    char *str ="1435687921000000";
    if(strptime (str, "%s", &tm) == NULL)
        exit(EXIT_FAILURE); 
    if(strftime (buffer,80,"%Y-%m-%d",&tm) == 0)
        exit(EXIT_FAILURE);

    printf("%s\n", buffer);

    return 0;
}


How to parellelize a program


I am a Physics researcher and i am doing Monte-Carlo simulations about magnetic properties of manganites. I wrote a program in C language and all is going fine except that the time of execution is so huge (maybe 1000 year depending in the size of Markov Chain and the size of the lattice). So I have no solution except that I have to parallelize my program and find a super-calculator. Of course I can't parallelize the whole program because if I do that I will lose the causality of the Markov Chain loop. I can parallelize only one loop inside the Markov Chain and this is sufficient. Here below a portion of my program showing the loop that I have to parellelize. If someone can tell me how to divide this loop into threads?

n = 1;

while(n <= Nc)
{
    fscanf(voisins,"%d%d%f%f%f%f",&i,&j,&r[0],&r[1],&r[2],&d);
    V = 0.0;E = 0.0;F = 0.0;

    for(p = 0;p < 3;p++)
    {
        V += (D/pow(d,3.0))*(spin[3*i-3+p]-w[p])*spin[3*j-3+p];
        E += (spin[3*i-3+p]-w[p])*r[p];
        F += spin[3*j-3+p]*r[p];
    }

    G = -3*(D/pow(d,5.0))*E*F;
    dU += (V+G);
    n++;
}


Implementation of Binary Search ( where array must be a pointer passed to function) [on hold]


Implementation of Binary Search

Write a C program to implement Binary Search Algorithm. Include a function int BinarySearch (int, int, int *, int x) --- The 1st parameter is the lower limit of the list or array, the 2nd parameter is the upper limit of the list or array, the third parameter is a pointer to the array and the fourth parameter is the search element. The index of the search element is returned by the function. If the search element is not present in the array, -1 is returned.

Function Definitions: int BinarySearch (int l, int h, int * a, int x)


CZMQ Multiple Poller


How could I have two poller in c code using czmq? (One of them use 5050 port another one use 5051)

I want to listen over this two ports and call appropriate function on message received for each port? What is the correct solution?


Use sphinx to create documentation of Python modules adding a module containing C wrappers


I am using sphinx to generate automatic documentation when writing my Python modules. Everything works fine till I want to add to the documentation also a section including a module having wrappers to C functions.

For instance, suppose that I have written a file c_module.c that look like this

#include <Python.h>

/*  wrapped function */
static PyObject* some_func(PyObject* self, PyObject* args)
{
    ...
}

/*  define functions in module */
static PyMethodDef CMethods[] =
{
     {"some_func", some_func, METH_VARARGS, ""},
     {NULL, NULL, 0, NULL}
};

/* module initialization */
PyMODINIT_FUNC

initcos_module(void)
{
     (void) Py_InitModule("c_module", CMethods);
}

where and how shall I put my comments so that sphinx is able to understand them? Moreover, what do I have to include in the index.rst file to add the documentation related to this c_module? Shall I add another rst file, somehow like "c_module.rst"? If so what should I put inside?

I came across the concept of "Domains" reading the sphinx documentation but I cannot understand the rationale behind them. Any help is really appreciated, thanks!


Parent process can't read all messages from 4 different pipes in C


Finally after reviewing and asking questions here, I was able to write this code which generates 4 child processes and communicate via 4 different pipes. Each of the 4 child processes writes into a single pipe (fd_log), but when the parent process reads from the pipe it reads only the first message from process A, the first message from process C, all messages from process B and none from process D. This is the code:

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

    printf("\nWritten by Nawar Youssef\n");
    int i, x=0, fd_log[2], fd_A_B[2], fd_B_C[2], fd_B_D[2], pipe_size=500;
    char ch, msg_from_A[pipe_size], msg_to_B[pipe_size], msg_to_log[pipe_size],
        msg_to_C[pipe_size], msg_to_D[pipe_size], msg_B_C[pipe_size], msg_B_D[pipe_size],
        msg_from_log[pipe_size], temp_char[pipe_size], msg_C_log[pipe_size], msg_D_log[pipe_size];

    pipe(fd_log);
    pipe(fd_A_B);
    pipe(fd_B_C);
    pipe(fd_B_D);

    if (fork()==0) { //child A
        for (i=0; i < 10; i++) {
            x = (rand() % 2);
            if (x == 1)
                ch='C';
            else
                ch='D';

            //write records to A-B pipe
            close(fd_A_B[READ]);
            sprintf(msg_to_B, "%c %d", ch, i);
            write(fd_A_B[WRITE], msg_to_B, strlen(msg_to_B)+1);

            //write records to log pipe
            close(fd_log[READ]);
            sprintf(msg_to_log, "A sent to B: %c %d", ch, i);
            write(fd_log[WRITE], msg_to_log, strlen(msg_to_log)+1);
        }//for
        close(fd_A_B[WRITE]);
        close(fd_log[WRITE]);
        _exit(1);
    }//if

    if (fork()==0) { //child B
        //read A-B pipe
        close(fd_A_B[WRITE]);
        int n_bytes = read(fd_A_B[READ], msg_from_A, sizeof(msg_from_A));
        for(i=0; i < pipe_size; i++) {

            if ( msg_from_A[i] == 'C') {

                //write the message from B to C pipe
                sprintf(msg_to_C, "%c %c", msg_from_A[i], msg_from_A[i+2]);
                //printf("--%s\n", msg_to_C);
                close(fd_B_C[READ]);
                write(fd_B_C[WRITE], msg_to_C, strlen(msg_to_C)+1);

                //write C message to log pipe
                close(fd_log[READ]);
                sprintf(msg_to_log, "B sent to C: %s", msg_to_C);
                write(fd_log[WRITE], msg_to_log, strlen(msg_to_log)+1);
                sleep(1);

            }else if (msg_from_A[i] == 'D') {

                //write the message from B to D pipes
                sprintf(msg_to_D, "%c %c", msg_from_A[i], msg_from_A[i+2]);
                //printf("--%s\n", msg_to_D);
                close(fd_B_D[READ]);
                write(fd_B_D[WRITE], msg_to_D, strlen(msg_to_D)+1);

                //write D message to log pipe
                close(fd_log[READ]);
                sprintf(msg_to_log, "B sent to D: %s", msg_to_D);
                write(fd_log[WRITE], msg_to_log, strlen(msg_to_log)+1);
                sleep(5);

            }else
                continue;
        }//for
        close(fd_B_C[WRITE]); close(fd_B_D[WRITE]); close(fd_log[WRITE]);
        _exit(1); //process B
    }//if

    if (fork()==0) { //child C
        //read from B-C pipe
        close(fd_B_C[WRITE]);
        int n_bytes = read(fd_B_C[READ], msg_B_C, sizeof(msg_B_C));
        for (i=0; i < pipe_size; i++) {

            //write to log pipe
            if (msg_B_C[i] == 'C') {
                sprintf(msg_C_log, "%c %c", msg_B_C[i], msg_B_C[i+2]);
                close(fd_log[READ]);
                sprintf(msg_to_log, "C sent to log: %s", msg_C_log);
                write(fd_log[WRITE], msg_to_log, strlen(msg_to_log)+1);
            }else
                continue;
        }
        _exit(1); //process C
    }

    if (fork()==0) { //child D
        //read from fd_B_D
        close(fd_B_D[WRITE]);
        int n_bytes = read(fd_B_D[READ], msg_B_D, sizeof(msg_B_D));
        for (i=0; i < pipe_size; i++) {

            //write to log pipe
            if (msg_B_D[i] == 'D') {
                sprintf(msg_D_log, "%c %c", msg_B_D[i], msg_B_C[i+2]);
                close(fd_log[READ]);
                sprintf(msg_to_log, "D sent to log: %s", msg_D_log);
                write(fd_log[WRITE], msg_to_log, strlen(msg_to_log)+1);
            }
        }
        _exit(1);
    }//if

    //parent
    close(fd_log[WRITE]);
    int n_bytes;
    while( (n_bytes = read(fd_log[READ], msg_from_log, sizeof(msg_from_log)-1)) > 0){
        printf("Log pipe reads (%d) bytes: %s\n", n_bytes, msg_from_log);
        sleep(1);
    }
    close(fd_log[READ]);
    return (0);
}

When I look at the output, I know that all messages were read (see in the output the number of bytes read returned). So it looks like the problem is in displaying the messages. I have faced a similar problem with much simpler code and I solved it by making pipe_size larger. But here it didn't work.
This is the output number between (#) is the bytes read each time the while loops:

Written by Nawar Youssef

Log pipe reads (187) bytes: A sent to B: C 0

Log pipe reads (36) bytes: C sent to log: C 0

Log pipe reads (17) bytes: B sent to C: C 2

Log pipe reads (35) bytes: B sent to D: D 3

Log pipe reads (17) bytes: B sent to D: D 4

Log pipe reads (17) bytes: B sent to D: D 5

Log pipe reads (17) bytes: B sent to D: D 6

Log pipe reads (17) bytes: B sent to D: D 7

Log pipe reads (17) bytes: B sent to C: C 8

Log pipe reads (17) bytes: B sent to C: C 9


Reversing a two dimensional character array in C


i am trying to write a program which reverses a entire string and also may print reversing each word of the string more than one time. For example my string is: "2 Fox jumps over the lazy dog." for this, the output should be: .god .god yzal yzal eht eht revo revo spmuj spmuj xoF xoF. I am trying to store each word in a 2d array and then reverse each word but i am not able to do that. here is my code. kindly help Note: how do we provide EOF in console

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

int main() {
    char string[100][100];
    char ch;
    int i = 0, j = 0, l = 0, count = 0, x = 0, y = 0;
    while ((ch = getchar()) != EOF) {
        string[i][l++] = ch;
        if (ch == ' ') {
            string[i][l] = '\n';
            i++;
            l = 0;
            count++;
        }
    }
    for (x = 0; x <= count; x++) {
        int length = strlen(string[x]) - 1;
        for (y = length; y >= 0; --y)
            printf("%s", string[y]);
    }
    return 0;
}


Freeing a multidimensional array when allocation fails


Say I allocate a two-dimensional array:

int main(void)
{
        long int **arr;
        int i;
        int j;

        arr = calloc(2, sizeof(long int *));
        if (!arr) {
                exit(EXIT_FAILURE);
        }

        for (i = 0; i < 2; i++) {
                arr[i] = calloc(10, sizeof(long int));
                if (!arr[i]) {
                        for (j = i; j > 0; j--) {
                                free(arr[j]);
                        }
                        free(arr);
                        exit(EXIT_FAILURE);
                }
        }
}

Should I include the free()-loop in the test condition if memory allocation fails

if (!arr[i]) {
        for (j = i; j > 0; j--) {
                free(arr[j]);
        }
        free(arr);
        exit(EXIT_FAILURE);
}

or is it usually enough to just exit() with failure when I don't want the program to move on?

if (!arr[i]) {
        exit(EXIT_FAILURE);
}


How do I directly access reserved memory with a kernel module?


I'm trying to limit the OS (Ubuntu Server 15.04) to a certain memory usage and reserve the rest but write a kernel module to read/write to the reserved memory. I figured out how to limit the usage/reserve memory using the kernel parameters "mem=4G memmap=4G@0 memmap=4G$4G" (4GB for OS and 4GB reserved, split at 4GB point) but I don't know how DMA to reserved memory works with kernel modules. I was thinking just create a proc file but I'm not sure if you can create one outside of the OS's allocated memory.

Any suggestions? Thanks!

Edit: This is for research so it doesn't need to be "nice"

Update: Maybe I don't need to write a kernel module. I just found this and I'm going to give it a shot: http://ift.tt/1HvU0rg

Update: I tried the link above but I segfault whenever I try to write. Here's my code:

    #include <fcntl.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/mann.h>

    #define RESERVED_MEMORY_SIZE 0x100000000

    int main() {
            int fd;
            char *reserved_memory;

            fd = open("/dev/mem", O_RDWR | O_SYNC);
            reserved_memory = (char *) mmap(0, RESERVED_MEMORY_SIZE, PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, fd, 4096);
            reserved_memory[0] = 'a';
            return 0;
    }

dmesg shows:

    a.out[1167]: segfault at ffffffffffffffff ip 00000000004005d7 sp 00007ffeffccbd80 error 7 in a.out[400000+1000]

For kicks I tried reserved_memory[1]:

    a.out[1180]: segfault at 0 ip 00000000004005db sp 00007ffc388d77b0 error 6 in a.out[400000+1000]

I'll look into the format of those messages so I can figure out what it's telling me.

Update:

I found this question by somebody with the same issue as me however the only solution appears to be a kernel rebuild. I'm going to try to avoid this so maybe my best option is a custom kernel module again. accessing mmaped /dev/mem?


What documentation tool am I expected to process this with?


I have a file distributed with an atmel library (at91lib), that looks as follows:

/**
 \page "AT91 USB device framework"

 AT91 USB %device framework is a device-side USB framework. It enables rapid
 development of USB-compliant class drivers such as the Mass Storage Device
 (MSD) or the Communication Device Class (CDC) and etc.

 This page shows the index to describe the AT91 USB %device framework.
 - USBD: USB Device

 -# "USB Device Framework Architecture"
 -# "USB Device Framework Description"
   -# "Standard USB Structures"
   -# "USBD API"

 [etc]
*/

/**
 \page "USB Device Framework Architecture"

 !!!Framework Architecture

 The following three-tiered structure is used:
 - A #hardware layer# which performs low-level operations on the USB controller.
 - The #USB API# offers hardware-independent methods and structures.
 - The #application layer#, made up of a USB class driver and the user
   application.
*/

Obviously, this is some kind of documentation comment system being used to document a directory. It also clearly produces HTML output, as the file contains an HTML image map at some point.

However, the !!! doesn't look like doxygen, nor does # for linking. Can anyone identify the documentation tool needed to process this to HTML?


Visual C++ 2013 - Windows XP Sp1 C Program Not Working - Blank Command Line


just created and compiled a simple "Hello world" in C in Visual Studio 2013 for testing purpose as some service I wrote didn't work on a Windows XP machine (yes I know it's ultra old, never mind).

So I thought I'd test with "hello world". I know that I need to select a Windows XP compatible environment in the General Settings of the Visual Studio project, done that. Tried MT and MD, so static or dynamic. Both gives me the same result: Nothing. Just a blank command line. I don't get it.

Any ideas what might be missing? I'm afraid I don't have full access on the XP system, just a command line shell, that's it. But I guess that wouldn't make a real difference.

I tried other command line tools which tend to work just fine, just my own compiled ones do nothing. Source code, just so noone asks ;-)

#include <stdio.h>
#include <Windows.h>

int main(int argc, char *argv[])
{
    printf("Hello World\n");
    return 0;
}

Hm...aaaannoying:-)


Multithreaded program goes in segmentation fault because of an argument


I'm having and odd problem with a multithreaded program of wich I will report only part of the code. When I try to run it I receive a segmentation fault error. Using gdb and valingrind I was able to find out that the problem is when I try to dereference info, such as in for(i=0; i<info->subm_n; i++). The strangest thing is that if I make the cast info=(c_args*)a after the strncpy(), it goes in segmentation fault only when collector's thread exits. I'm using a 64 bit OS and I've read that this sometimes can make problems while casting to void* in pthread_create(), I don't even know if that's the case. Anyone has any idea? P.S. System calls with capital letters are just redefinition of the functions in witch I also test for fails

typedef struct collector_arguments{
  int subm_n;
  int chronon;
   planet_t *p;
}c_args;


static void* collector(void* a) {
  int fd_skt,fd_sincro,tmp,i=0;
   c_args *info;
   struct sockaddr_un sa;
   info=(c_args*) a;

  strncpy(sa.sun_path,"visual.sck" ,MAXPATH);
  sa.sun_family=AF_UNIX;

  if((fd_sincro=open("SINCRO",O_RDWR))==-1) {
      perror("collector unable to open SINCRO fifo");fflush(stdout);
      pthread_exit(&errno);
   }
  for(i=0; i<info->subm_n; i++) {
    if (read(fd_sincro,&tmp,sizeof(int))==-1){
         perror ("collector Unable to read");fflush(stdout);
         pthread_exit(&errno);
    }
    fd_skt=Socket(AF_UNIX,SOCK_STREAM,0);
    while (connect(fd_skt,(struct sockaddr*)&sa, sizeof(sa)) == -1 ) {
        if ( errno == ENOENT )  sleep(1);
        else {
            perror ("client unable to connect to socket");fflush(stdout);
            pthread_exit (&errno);
        }
    }
    Write(fd_skt,&i,sizeof(int));
    Close(fd_skt);
  }
  Close(fd_sincro);
  pthread_exit((void*) 0);
}




static pthread_mutex_t fifo_mtx = PTHREAD_MUTEX_INITIALIZER;

static void* dispatcher(void* a) {
coordinate *c;
wator_t* w;
int i,j,fifo;
pthread_t tid_collector;

c_args *info=malloc (sizeof(c_args));
w=(wator_t*) a; 
c=(coordinate*) malloc(sizeof(coordinate));
c->numr=2;
c->numc=2;
while ( ((w->plan->nrow / c->numr) * (w->plan->ncol / c->numc))>NWORK_DEF && (w->plan->nrow > 2*c->numr) && (w->plan->ncol > 2*c->numc) ){
    if ( (w->plan->nrow / c->numr) >= (w->plan->ncol / c->numc) )       
        c->numr=c->numr*2;
    else 
        c->numc=c->numc*2;
    }


if ((w->plan->nrow % c->numr)==0) i=(w->plan->nrow / c->numr);
else i=(w->plan->nrow / c->numr)+1;
if ((w->plan->ncol % c->numc)==0) j=(w->plan->ncol / c->numc);
else j=(w->plan->ncol / c->numc)+1;
info->subm_n=i*j;
info->chronon=0;
info->p=w->plan;
while(1){
    reset_updated(w);
    (info->chronon)++;

    Pt_create( &tid_collector, NULL,&collector,(void*) info);

    for(i=0; i< w->plan->nrow; i+=c->numr)
        for(j=0; j< w->plan->ncol; j+=c->numc){     
            if((fifo=open("FIFO",O_WRONLY))==-1){
                perror("dispatcher unable to open FIFO");fflush(stdout);
                pthread_exit(&errno);
                }
            c->rowi=i;
            c->coli=j;
            Write(fifo, c, sizeof(*c));
            Close(fifo);
            }
    i=( (i/c->numr) * (j/c->numc) );
    Pt_join( tid_collector,NULL);
    }
return NULL;
}


Code modification for an array of numbers to be read from pointer


I have the following code: value represents an array of numbers. I want to arrange all numbers while also keeping track of the max and min.

if (value > stats_max)
    stats_max = value;
if (value < stats_min)
    stats_min = value;

can I do:

if ((value > stats_min) && (value < stats_max))
     stats_mid = value;

just to print one value.

what should I do to write all those "values" in an array?


Printing Bitwise NOT operator with hexadecimal format specifier [on hold]


If i'm using m instead of ~m then the code gives me the expected hexadecimal value of 32 but here it's giving ffffffdf as output.

EDIT I know how bitwise ~ NOT operator works. But i'm not understanding this.Could somebody explain this...??

#include<stdio.h>

int main()
{
    unsigned int m = 32;
    printf("%x\n", ~m); //ffffffdf is printed as output

    return 0;
}


Convert mixed JSON-Number-Array to int, uint, float using lib rapidjson


As I understood this char* is a valid json-string.

const char* json = { "array":[14, -15, 3.17], "array_type": ["uint", "int", "float"] }

All numbers in the array shall be 4 bytes.

How could one loop through the array using rapidjson?

This is my code so far:

int i_val; uint ui_val; float f_val;
Document d;

d.Parse(json);
Value& a = d["array"]; Value& at = d["array_type"];

for(SizeType i=0; i<a.Size();i++) //<-- Crashes here, after accessing the double value
{
   if(a[i].IsInt() && (string)at[i].GetString()=="int")
   {
      i_val=a[i].GetInt();
      //Do anything
   }
   if(a[i].IsUint() && (string)at[i].GetString()=="uint")
   {
      ui_val=a[i].GetUint();
      //Do anything
   }
   if(a[i].IsDouble() && (string)at[i].GetString()=="float")
   {
      f_val=(float) a[i].GetDouble();
      //Do anything
   }
}

I know the last "if" is wrong and thats probably why the program crashes. Double is 8 bytes and the SizeType is 4 bytes by default.

Is there a solution to loop though the array?? If not I also would be good with other libs.. I need to transport these three different types of values by json. By the way the length of the array could be 1 to 500.

(There is no GetFloat() function.)

Thanks for any kind of help. Regards


Dynamic array's in C


I am trying to dynamically create an array of rectangles with random values. However when trying to access the space I malloc I get a seg fault.

My Code:

typedef struct Point
{
    double x;
    double y;
} PointT;

typedef struct Rect
{
    PointT location;
    char color;
    double w; //width
    double h; //height
} RectT;
main()
{
    RectT *recs;
    randRect(&recs);
}
void randRect(RectT **rects)
{
    int i;
    rects =malloc(numRec*sizeof(RectT*));
    for(i = 0; i < numRec-1; i++)
    {
          rects[i]->w=rand()%20;
          rects[i]->h=rand()%20;
          rects[i]->location.x=rand()%20;
          rects[i]->location.y=rand()%20;
    }
}

numRec is defined as 50


Possible to autogenerate Cython bindings around a large, existing C library?


In otherwords: *.h/*.c --[??POSSIBLE??]--> *.pxd/*.pyx

OK. I’ve done (I hope) enough digging around the Internet - but I think this is a good question so I’ll ask it straight.

There are a few related questions (e.g. Generate python bindings, what methods/programs to use or Wrapping a C library in Python: C, Cython or ctypes? ) but which don't quite sum up the situation that I’m asking which is perhaps for a more “high-level” approach (and specifically for an existing library, not generating new C from python).

I’ve got a little bit of experience of this myself having wrapped a wee bit of code before using Cython. Cython gets the thumbs up for speed and maintainability. That’s OK in my book for small/single bits of code - but, this time I’ve got a bit more on my plate…

And following the first of the three great virtues of a programmer - I want to do this with as minimal effort as possible.

So the real question here is how can I ease the creation by automated means of the .pxd, and possibly .pyx, files (i.e. to save time and not slip up miss-typing something).

This here seems to be the only real hint/note about how to do this - but most of the projects on it are defunct, old or sourceforge. Many only seem to work for C++ (this is C I'm doing here).

Does anyone still use them? Recently? Has anyone got a workflow or best practice for doing this? Am I simply just better doing it by hand?

My library is well defined by a set of header files. One containing defs of all the C struct/types and another containing prototypes for all the functions. But it's loooonnnggg...

Thanks for any tips.


How to add an int at the end of an uint8_t*?


I have a variable :

uint8_t* data

And I want to add a header to these data. Exactly two numbers. I want my data like these : data+my_int+my_second_int

After that I have to give my data to a function (that I can't modify), and the size of my data.

Like this : myfunction(data,size);

This is currently what my code looks like :

struct Data {
  uin8_t* data;
  uint32_t PTS;
  uint32_t DTS;
  uint16_t size_data;
};


struct Data* mydata;
mydata->data = data; // data I get before
mydata->size_daza = size; // size I get before
mydata->PTS = GST_BUFFER_PTS(buf);
mydata->DTS = GST_BUFFER_DTS(buf);

myfunction(mydata,sizeof(struct Data)); // My function , this function add also a header to my data (another).I can't access or modify this function.

After this, multiple things happend (doesn't matter what) and at the end another function delete the header appended with 'myfunction',then I cast the data given by this function in struct Data*. I can access to DTS, PTS , size but I have a SIGSEGV error on the data..

I think I have to change my Structure but i don't see an other manner to store a buffer without a pointer.


How to declare a void pointer in C? [on hold]


I'm trying to declare a void pointer in C using the following syntax:

void *vptr=0;

However, this code produces an error. What's the correct way to do this?


using assembly language with C [on hold]


I have some questions about the following code. What does "0" mean? The code is designed for the x86 system.

register int r_outa asm("0");
register int r_outb asm("3");
register int r_outc asm("2");

Additionally, I want to modify the above code to make it run in ARM system. What should I do?


C programming error.2Darrays


I have the code below.The problem is that I am taking a two dimensional array with a rows and 2 col.The 1st col is for storing values and 2nd as a flag.The problem arises when I initialize my flag the values are also getting affected.

#include<stdio.h>
    int main()
    {
        int a,b;
        scanf("%d%d",&a,&b);
        int arr[a][1];
        int i,j,k,sum=0;

        for(i=0;i<a;i++)
        {

            scanf("%d",&arr[i][0]);
        }
        for(i=0;i<a;i++)
        {

            printf("%d\n",arr[i][0]);
        }

        for(j=0;j<a;j++)
        {

           arr[j][1]=0;
        }
     for(i=0;i<a;i++)
        {

            printf("%d\n",arr[i][0]);//Different Values
        }
    }


Moving a character in a table


I just started learning programming languages and I want to make a character (point '*') in a table move.

This is my code

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

int main() {
    int v;
    int x = 50, y = 10;
    int i, j;
    char screen[80][25];

    // declare and initialize table
    for (i = 0; i < 80; i++)
        for (j = 0; j < 25; j++)
            screen[i][j] = ' ';

    // coordinate system
    for (i = 0; i < 80; i++) screen[i][12] =  '-';
    for (j = 0; j < 25; j++) screen[40][j] =  '|';

    // point, position
    screen[x][y] = '*';

    // print result
    for (j = 0; j < 25; j++) {
        for (i = 0; i < 80; i++)
            printf("%c", screen[i][j]);
        printf("\n");
    }
}

This prints a table of size 80x25 and a coordinate system with a centre in (40,12). I set the position of the character '*' on coordinates (x,y). I defined x and y as 50 and 10.

Now I want to move my star by changing x and y. How do I change x and y (position of the star)? Maybe with scanf function? I tried to use scanf like this:

int v;
...
scanf("%d", &v);
if(v == 1)
{
    y--;
}

but then everything (table, coordinate system and the character) disappeared. Please help.

Thanks.


lundi 29 juin 2015

How to validate if a xml file is valid with c/c++?


I don't want to use a xml parser. I just want to validate if the xml file's format is xml file.And for some file like this: I have some other characters before the file header. I'd like to consider it's a correct xml format.How to achieve with C/C++?


Reading text into a linked list using structs in C


I'm attempting to create a linked list using a struct from a txt file. Initially, I'm testing it with a txt file with only one line of information. This code compiles correctly, however when I run it, it returns "Line...didn't scan properly". As an aside, if I remove the if statement that returns such a value I get complete gibberish. I have no clue why the line isn't being scanned correctly, however I feel as though it may having something to do with the hyphen/plus sign in two of the terms that I tried to scan as strings. Thank you very much for any help you can provide.

This is the txt file:

1 20959U 90103A   14091.58762725 -.00000015  00000-0  00000+0 0  3197

This is the tester.c file:

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

typedef struct noradData {
    // line one
    int                lineNum;
    char             * satNum;
    char             * intDesig;
    float              epoch;
    float              firstTimeDeriv;
    char             * secondTimeDeriv;
    char             * drag;
    int                zero;
    int                set;
    struct noradData * next;
} Data; 

Data * first = NULL, * last = NULL;

int main() {
    char line[80], secondTimeDeriv[7], drag[7], satNum[6], intDesig[6];
    int lineNum, zero, set; 
    float epoch, firstTimeDeriv;

    FILE * fIn;
    Data * node;

    fIn = fopen("data1.txt", "r");
    if (fIn == NULL) {
        printf("Cannot open file\n");
        return 1;
    }

    while (fgets(line, sizeof(line), fIn) != NULL) {
        // Check line for various problems (too short, too long).
        if (line[0] == '\0') {
            printf ("Line too short\n");
            return 1;
        }

        if (line[strlen (line)-1] != '\n') {
            printf ("Line starting with '%s' is too long\n", line);
            return 1;
        }

        line[strlen (line)-1] = '\0';

        // Scan the individual fields.

        if (scanf("%d %s %s %f %f %s %s %d %d", &lineNum, satNum, intDesig, 
                &epoch, &firstTimeDeriv, secondTimeDeriv, drag, &zero, &set) 
                != 9) {
            printf ("Line '%s' didn't scan properly\n", line);
            return 1;
        }

        node = malloc(sizeof(Data));
        if (node == NULL) {
            printf ("Ran out of memory\n");
            return 1;
        }

        node->lineNum = lineNum;
        node->satNum = strdup(satNum);
        node->intDesig = strdup (intDesig);
        node->epoch = epoch;
        node->firstTimeDeriv = firstTimeDeriv;
        node->secondTimeDeriv = strdup(secondTimeDeriv);
        node->drag = strdup(drag);
        node->zero = zero;
        node->set = set;
        node->next = NULL;

        if (first != NULL) {
            last->next = node;
            last = node;
        }
        else {
            first = node;
            last = node;
        }
    }
    fclose (fIn);
    node = first;
    while (node != NULL) {
        printf("%d %s %s %f %f %s %s %d %d", node->lineNum, node->satNum, 
            node->intDesig, node->epoch, node->firstTimeDeriv, 
            node->secondTimeDeriv, node->drag, node->zero, node->set);
        node = node->next;
    }
    return 0;
}


C: ADD duplicate items(string) in doubly linked list


I am learning C and currently figuring out the implementation of double linked list. As strange as it may sound, I want repetitive items added to my linked list. I am adding newNode to the list in sorted order.

The below function does not add the repetitive nodes. I will be thankful for any assistance

    struct Node
    {
        char name[42];
        struct Node *next;
        struct Node *prev;
    };

    void addSorted(struct Node **head, struct Node *newNode)
    {
        struct Node* current;
        // Special case for the head end
        if ((*head == NULL) || strcmp((*head)->name, newNode->name) >= 0)
        {
            newNode->next = *head;
            *head = newNode;
        }
        else
        {
            // Locate the Node before the point of insertion
            current = *head;
            while (current->next != NULL &&
                    strcmp(current->next->name, newNode->name) <= 0)
            {
                current = current->next;
            }
            newNode->next = current->next;
            current->next = newNode;
        }
    }

    struct Node* GetNewNode(char *name)
    {
        struct Node* newNode = malloc(sizeof (struct Node));

        strcpy(newNode->name, name);
        newNode->prev = NULL;
        newNode->next = NULL;

        return newNode;
    }

    int main(void)
    {
        // Some Irrelevant Code
        if (strncmp(operator, "a", 1) == 0)
        {
            temp = GetNewNode(name);

            addSorted(&head, temp);
        }
     }


How to compile C code that #includes C++ code?


I have to compile generated C code that #includes C++ headers and it get it to work on Linux, OS X and Windows. I put the #includes myself to be able to interact with C++ code from it.

The C code however is such that a strict compiler would catch errors that could be treated as warnings. I want to pass these off as warnings as most of this is generated code which I don't have control over.

Here are my attempts to compile it (I use CMake, btw):

(I use these flags: -Wno-write-strings -Wno-error -fpermissive)

  • Treat the entire project as C++ code: works on Linux (with g++) but on OS X I get:

With Clang:

error: assigning to 'char *' from incompatible type 'const char *'

With g++:

/var/folders/hf/5dbkbqrx5p3bmnpdqqy4wgpr0000gn/T//ccvMHo2S.s:18:no such instruction: `vmovdqa LC0(%rip), %xmm3'
/var/folders/hf/5dbkbqrx5p3bmnpdqqy4wgpr0000gn/T//ccvMHo2S.s:19:no such instruction: `vmovdqa LC1(%rip), %xmm2'
/var/folders/hf/5dbkbqrx5p3bmnpdqqy4wgpr0000gn/T//ccvMHo2S.s:20:no such instruction: `vmovdqu (%rsi), %xmm7'
/var/folders/hf/5dbkbqrx5p3bmnpdqqy4wgpr0000gn/T//ccvMHo2S.s:21:no such instruction: `vmovdqu 16(%rsi), %xmm8'
/var/folders/hf/5dbkbqrx5p3bmnpdqqy4wgpr0000gn/T//ccvMHo2S.s:22:no such instruction: `vmovdqa LC2(%rip), %xmm1'
/var/folders/hf/5dbkbqrx5p3bmnpdqqy4wgpr0000gn/T//ccvMHo2S.s:23:no such instruction: `vpshufb %xmm3, %xmm7,%xmm6'

  • Treat C code as C code:

Doesn't find <atomic>

 fatal error: atomic: No such file or directory
 #include <atomic>

Flag becomes invalid.

clang: error: unknown argument: '-q'
clang: warning: treating 'c' input as 'c++' when in C++ mode, this behavior is deprecated

How do I go about building this?