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?