mardi 4 août 2015

Headers Vs. Static Libraries

I am planning to do some utility code for using in other projects, but I am doubting between making it a mostly-headers code, a static library with headers just exposing the interface or something in between. Most of the code will be simple functions that wrap other standard functions but there will be also some bigger functions.

I think I mostly understand the differences between the header approach and the static library approach:

For the headers:

  • All the code will be in headers
  • Better oportunities for the compiler to inline code
  • Every function will have to be compiled every time it is used

For the static library:

  • Mixed code between the library and the headers
  • Worse oportunities for the compiler to inline code
  • Compile once and forget

I have been looking at some code and I have seen both approaches, but I don't know which will be better. Any thoughts?

Is there a difference in speed between using const and static const inside a function?

In C, what is the difference between static const and const inside a function?

For instance, take the given code examples:

void print_int(int x) {
  assert( x < 5 && x > -5 );
  const int i[9] = {
    -4, -3, -2, -1, 0, 1, 2, 3, 4
  };
  printf("%i", i[x + 4]);
}
int main() {
  print_int( 1 );
  return 0;
}

Versus:

void print_int(int x) {
  assert( x < 5 && x > -5 );
  static const int i[9] = {
    -4, -3, -2, -1, 0, 1, 2, 3, 4
  };
  printf("%i", i[x + 4]);
}
int main() {
  print_int(1);
  return 0;
}

Would the generated assembly be optimized better if I used static const instead of const, or would the output be the same for both examples?

Eclipse error when trying to run C code

I'm trying to understand binary and hexadecimal numbers. I want to know why my program won't launch in eclipse. It gives me this error:

launch has encountered a problem

It was running when i used int. My computer is 64bit. I'm trying to understand hardware. I need to know what I'm doing wrong. What can I improve on? Is it okay to declare buffer as a global variable? Thanks.

My code is here.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * convertBase(unsigned long int numberToConvert, long int base)
{

    char buffer[65];
    char *pConvertedNumber;
    char allValues[] = "0123456789abcdef";

    pConvertedNumber = &buffer[sizeof(buffer)-1];

    *pConvertedNumber = '\0';

    do {

        int value = numberToConvert % base;

        pConvertedNumber = pConvertedNumber - 1;

        *pConvertedNumber = allValues[value];

        numberToConvert /= base;

    } while(numberToConvert != 0);

    printf("%s", pConvertedNumber);

    return pConvertedNumber;
}

int main(void){

    unsigned long int numberOne = 1000000000;
    printf("\n%ld in Base 16 = ", numberOne);
    convertBase(numberOne, 16);

    printf("\n");

return 0;
}

How to control multiple robots through raspberry pi using bluetooth

I am trying to control two arduino robots through raspberry pi using Bluetooth, I have already created the rfcomm file to control one robot, should i include the address of the second one in same rfcomm file? if yes, could someone please tell me how?I've done this is it correct?please ignore the 'enter code here' part everywhere

RFCOMM configuration file.

enter code hererfcomm0 { enter code here # Automatically bind the device at startup enter code here bind yes;

   `enter code here` # Bluetooth address of the device
    `enter code here`device 30:14:10:15:20:90;


   `enter code here` # RFCOMM channel for the connection
   `enter code here` channel 0;


    `enter code here`# Description of the connection
    `enter code here`comment "Example Bluetooth device";

enter code here}

enter code hererfcomm1 { enter code here# Automatically bind the device at startup enter code herebind yes;

   `enter code here`# Bluetooth address of the device

   `enter code here` device 10:14:06:16:00:09;

  `enter code here` # RFCOMM channel for the connection
  `enter code here`  channel 0;

`enter code here` # Description of the connection
`enter code here`    comment "Example Bluetooth device";

enter code here}`

How to store 3 different types of data in one array

I need to store 3 linked bits of data in c. My original thought was a 3 dimensional array but that won't work as all 3 data types are different. The top level needs to be a char array. The second level needs to be a date/time so a integer. The third level is a temperature reading so needs to be a float.

Is the correct way to do this an array of pointers pointing to an array of pointers pointing to a array of floats? If so how would that be written in C?

Is there any limit to the number of expressions|parameters in a 'while loop' [duplicate]

This question already has an answer here:

Traditional programming with while-loop is done with a single parameter ex:

  • while(1) (or) while(a==b) (or) while(a&&b) (or) while(!a) etc
  • The code below takes two parameters in the while loop

    ssize_t r_read(int fd, void *buf, size_t size) 
    {
        ssize_t retval;
        while (retval = read(fd, buf, size), retval == -1 && errno == EINTR);
        return retval;
    }
    
    
    1. Is there any limit to the parameters inside the while loop?
    2. Is there any possible explanation for this or does this methodology have a name?

8 Bit (Binary) array checking in c (embedded c)

I have an array a[j] . In it has an 8 bit binary digit . I need to check each bit whether it was zero or one . How to write the program in C .

Modify if-counter inside a loop

I'm trying to modify a counter in if loop because one array index number needs to be corresponded by the other in order for me to change the place of it's text, but the space between the strings add 1 to the counter.

for(int i = 0, n = strlen(p); i < n; i++){

    if(isspace(p[i])){
        c1 = x[i-1];
        printf("%c", p[i]);
    }
    if(isalpha(p[i])){
        c1 = x[i];
        c2 = c1-96;
        printf("%c --- %c ---%d\n",p[i],c1, c2);
    }

This is one of the attempts but it made an infinite loop, I've tried different approach like:

    if(isspace(p[i))){
        printf("%c", p[i]);
        i -= 1;
    }

C: Zlib compress not working

I'm trying a very simple thing: read a minimal text file and compress it with the compress() utility from zlib. I think I've done everything fine, I allocate filesize * 10 for the output, it should be more that enough, but I keep getting -5 (Z_BUF_ERROR) as result of the operation. Any help?

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

#define FILE_TO_OPEN "text.txt"

static char* readcontent(const char *filename, int* size)
{
    char* fcontent = NULL;
    int fsize = 0;
    FILE* fp = fopen(filename, "r");

    if(fp) {
        fseek(fp, 0, SEEK_END);
        fsize = ftell(fp);
        rewind(fp);

        fcontent = (char*) malloc(sizeof(char) * fsize);
        fread(fcontent, 1, fsize, fp);

        fclose(fp);
    }

    *size = fsize;
    return fcontent;
}

int main(int argc, char const *argv[])
{
    int input_size;
    char* content_of_file = readcontent(FILE_TO_OPEN, &input_size);

    printf("%d\n", input_size);

    uLongf compressed_data_size;
    char* compressed_data = malloc(sizeof(char) * (input_size * 10));

    int result = compress((Bytef*) compressed_data, (uLongf*)&compressed_data_size, (const Bytef*)content_of_file, (uLongf)input_size);
    printf("%d\n", result);

    return 0;
}

Why does my program display the Array address instead of its contents?

My C program consists of an array called 'test_var'. It has another integer array 'arr_int' that consists of a set of integer numbers. My code looks something like this:

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

 int State(var);
 int main()
       {
         int arr_int[3] ={1000, 1001, 1002, 1003};
         int var;
         int *test_var[4]={0};

         State(var)
         {
            int i;
            for(i=0; i<4; i++){
               test_var[i] = arr_int[i];
               i++;
                }
          return test_var[var];
          }

          printf("Enter a number between 0 and 3\n");
          scanf("%d",&var);   
          State(var);
          printf ("The array structure is %d", test_var[var]);

          return 0;
          }

However now when I try to print the returned value array test_var for the user input var=0 instead of the whole array(1000) I just get 0. What am I doing wrong here ? COuld somebody please tell me? Am I dereferencing the array in a wrong way?

Efficient way to copying array of pointer to another pointer

How to copy array of pointer to another pointer.

My approach this way

int *ptr2[(i-1)*100];
int *ptr1;

ptr1=&ptr2[(i-1)*100];

What is the efficient way to copy so that it takes less cpu cycle.

Compiling on Mac

I am brand new to this forum, and have just begun to learn C. The book I am going through wants me to compile the code that was written. I have a file "cards.c", I am on a Mac, have Xcode installed, downloaded gcc from Apple and installed it.

gcc -v Configured with: --prefix=/Applications/http://ift.tt/1d5DwEL --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn) Target: x86_64-apple-darwin14.4.0 Thread model: posix

When I type: gcc cards.c -o cards

I get: clang: error: no such file or directory: 'cards.c' clang: error: no input files

I have tried going to Xcode downloads to install Xcode's Command Line Tools, it doesn't show up there, maybe I have a newer version?

I cannot figure out how to compile this, any ideas on what I am doing wrong?

Does the cards.c file need to be in a specific folder somewhere?

Expose c-library functionality to node

I have been working on using a c library in my node project. After little bit investigation I found node-gyp.

I was successfully able to execute example but when I am trying to using third party c library functions in the code it was giving me linking error on run time.

Library can be found here http://ift.tt/1SZL7q7

I compiled the library independently to have *.a objects

I am using following example http://ift.tt/1KO1IOs

So I have following questions as I can infer

  • Shall I convert bibutils from make to gyp?
  • Shall I convert each source file to work with V8? I don't know how to do this.
  • How can I easily link this project to work with node-gyp with less noise?

Details related to script can be found below. bibutils folder is placed along with addon.cc

binding.gyp looks like

{
  "targets": [
    {
      "target_name": "addon",
      "sources": [ "addon.cc" ],
      "include_dirs": ["bibutils/lib"],
      "library_dirs": ["bibutils/lib/libbibutil.a","bibutils/lib/libbibprogs.a"]
    }
  ]
}

modified addon.cc

#include <node.h>
#include "bibutils.h"
#include "bibprogs.h"

using namespace v8;

void MyFunction(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
      /****This is not production code just to check the execution***/
      bibl b;   
      bibl_init( &b );
      bibl_free( &b );
      /**************************************************************/
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world"));
}

void CreateFunction(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);
  Local<Function> fn = tpl->GetFunction();

  // omit this to make it anonymous
  fn->SetName(String::NewFromUtf8(isolate, "theFunction"));

  args.GetReturnValue().Set(fn);
}

Compilation Result

user1@ubuntu:~/node-addon-examples/5_function_factory/node_0.12$ npm install

> function_factory@0.0.0 install /home/user1/node-addon-examples/5_function_factory/node_0.12
> node-gyp rebuild

make: Entering directory `/home/user1/node-addon-examples/5_function_factory/node_0.12/build'
  CXX(target) Release/obj.target/addon/addon.o
  SOLINK_MODULE(target) Release/obj.target/addon.node
  COPY Release/addon.node
make: Leaving directory `/home/user1/node-addon-examples/5_function_factory/node_0.12/build'

On Execution

user1@ubuntu:~/node-addon-examples/5_function_factory/node_0.12$ node addon.js
node: symbol lookup error: /home/user1/node-addon-examples/5_function_factory/node_0.12/build/Release/addon.node: undefined symbol: _Z9bibl_initP4bibl

Debug Info:

user1@ubuntu:~/node-addon-examples/5_function_factory/node_0.12$ nm -C build/Release/addon.node | grep bibl_init
                 U bibl_init(bibl*)

Custom DNS answers

I'm currently working on a project for my summer internship and I've got to make an oblivious DNS translation server. I'm not here to speak about the oblivious part in detail but I'll explane the architecture of my program.

There is a server side that receives obfuscated requests and sends back an answer that it doesn't understand itself.

On the client side there is a proxy that translate requests into obfuscated requests. For that I use an iptables rule to send all DNS requests to a NFQUEUE, and then I work with libnetfilter_queue to handle the packet. After that I received the answer from the server I make a DNS answer with all the information I get (from the DNS request and from the server) and send it using libnet.

Now let's talk about my problem : When using my proxy I check the traffic with Wireshark and it seems that my proxy sends valid answers but if I try to browse the Internet with Firefox it doesn't work. You can find my code here : http://ift.tt/1SZL7pX

Is there a problem in my way of building DNS packets ?

Here is the DNS sender :

int send_answer(char *dst_ip_array, char *src_ip_array, int dport, int sport, int dns_id, char *query, char *req_ip, int logfd)
{
char c;
u_long src_ip = arrayToLong(src_ip_array), dst_ip = arrayToLong(dst_ip_array), requested_ip_long=dotToLong(req_ip);
char requested_ip[4];
u_short type = LIBNET_UDP_DNSV4_H;
libnet_t *l;

libnet_ptag_t ip;
libnet_ptag_t ptag4; /* TCP or UDP ptag */
libnet_ptag_t dns;

char errbuf[LIBNET_ERRBUF_SIZE];
char payload[1024];
u_short payload_s;
char log_buffer[500];
int length = 0;

/*
 *  Initialize the library.  Root priviledges are required.
 */
l = libnet_init(
        LIBNET_RAW4,                            /* injection type */
        NULL,                                   /* network interface */
        errbuf);                                /* error buffer */

if (!l)
{
    length += sprintf(log_buffer + length, "\tlibnet_init: %s", errbuf);
    exit(EXIT_FAILURE);
}

/* 
 * build dns payload 
 */
requested_ip[0]=requested_ip_long/(256*256*256);
requested_ip_long=requested_ip_long%(256*256*256);
requested_ip[1]=requested_ip_long/(256*256);
requested_ip_long=requested_ip_long%(256*256);
requested_ip[2]=requested_ip_long/256;
requested_ip_long=requested_ip_long%256;
requested_ip[3]=requested_ip_long;

payload_s = snprintf(payload, sizeof payload, "%c%s%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c", 
         (char)(strlen(query)&0xff), query, 0x00, 0x00, 0x01, 0x00, 0x01, 0xc0, 0x0c, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x0d, 0xe0, 0x00, 0x04, requested_ip[0], requested_ip[1], requested_ip[2], requested_ip[3]);

/* 
 * build packet
 */
dns = libnet_build_dnsv4(
type,          /* TCP or UDP */
dns_id,        /* id */
0x8100,        /* request */
1,             /* num_q */
1,             /* num_anws_rr */
0,             /* num_auth_rr */
0,             /* num_addi_rr */
payload,
payload_s,
l,
0
);

if (dns == -1)
{
    length += sprintf(log_buffer + length, "\tCan't build  DNS packet: %s\n", libnet_geterror(l));
    goto bad;
}

ptag4 = libnet_build_udp(
    sport,                                /* source port */
    dport,                                    /* destination port */
    LIBNET_UDP_H + LIBNET_UDP_DNSV4_H + payload_s, /* packet length */
    0,                                      /* checksum */
    NULL,                                   /* payload */
    0,                                      /* payload size */
    l,                                      /* libnet handle */
    0);                                     /* libnet id */

if (ptag4 == -1)
{
    length += sprintf(log_buffer + length, "\tCan't build UDP header: %s\n", libnet_geterror(l));
    goto bad;
}


ip = libnet_build_ipv4(
    LIBNET_IPV4_H + LIBNET_UDP_H + type + payload_s,/* length */
    0,                                          /* TOS */
    242,                                        /* IP ID */
    0,                                          /* IP Frag */
    64,                                         /* TTL */
    IPPROTO_UDP,                                /* protocol */
    0,                                          /* checksum */
    src_ip,                                     /* source IP */
    dst_ip,                                     /* destination IP */
    NULL,                                       /* payload */
    0,                                          /* payload size */
    l,                                          /* libnet handle */
    0);                                         /* libnet id */

if (ip == -1)
{
    length += sprintf(log_buffer + length, "\tCan't build IP header: %s\n", libnet_geterror(l));
    exit(EXIT_FAILURE);
}


/*
 * write to the wire
 */
c = libnet_write(l);
if (c == -1)
{
    length += sprintf(log_buffer + length, "\tWrite error: %s\n", libnet_geterror(l));
    goto bad;
}
else
{
    length += sprintf(log_buffer + length, "\tWrote %d byte DNS packet; check the wire.\n", c);
}
length = strlen(log_buffer);
write(logfd, log_buffer, length); // Write to the log.
libnet_destroy(l);
return (EXIT_SUCCESS);
bad:
length = strlen(log_buffer);
write(logfd, log_buffer, length); // Write to the log.
libnet_destroy(l);
return (EXIT_FAILURE);
}

Here is an example of DNS answer sent by my proxy: http://ift.tt/1KO1GGw

Are there ready-to-use solutions (libraries, headers) or standard pattern/workflow for reading (a lot) input parameters? [on hold]

Heyho,

my situation

I have a quite big scientific c-program that needs a lot of input parameters reading out of a file. I have a "handmade" working version from the ones, working on the program before. But you have to keep a special order of the parameters, the formatted input file is kind of unhandy, adding of parameters is complicated and it is kind of error sensitive.

my ideas so far

If been looking for a while in different c introduction books and also in some advanced techniques guides, but nobody seems to write something about these kind of tasks.

The only thing, I could find, was the idea to use an external program that creates out of handy interface the sorted, unhandy to use directly input file I'm now using. But that takes more time and for adding/sorting/deleting parameters I have to change the program code and the input file generator.

my question

What kind of input handling strategy are there? Are there special coding techniques? Or a common workflow?

Please ask, if I have to specify things. I'm not use to common names and notations, sorry for that. Please correct me referring to this.

Handling Decimals on Embedded C

I have my code below and I want to ask what's the best way in solving numbers (division, multiplication, logarithm, exponents) up to 4 decimals places? I'm using PIC16F1789 as my device.

float sensorValue;
float sensorAverage;

void main(){
    //Get an average data by testing 100 times
    for(int x = 0; x < 100; x++){
        // Get the total sum of all 100 data
        sensorValue = (sensorValue + ADC_GetConversion(SENSOR));
    }

    // Get the average
    sensorAverage = sensorValue/100.0;
}

How to get disk name programmatically in Linux(Like "/dev/sda" or "/dev/sdb")?

I am trying out to find information related to Disk and partitions. Following are my code. But problem is that, I am passing disk name through command line by querying disk name from "/proc/partitions". Is there any api which can give me disk name as well.

#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <blkid/blkid.h>

int main (int argc, char *argv[])
{
 blkid_probe pr;
 blkid_partlist ls;
 int nparts, i;

 pr = blkid_new_probe_from_filename(argv[1]);
 if (!pr)
 err(2, "faild to open device %s", argv[1]);

 ls = blkid_probe_get_partitions(pr);
 nparts = blkid_partlist_numof_partitions(ls);

for (i = 0; i < nparts; i++)
{
blkid_partition par = blkid_partlist_get_partition(ls, i);
printf("PartNo = %d\npart_start = %llu\npart_size =  %llu\npart_type = 0x%x\n",
blkid_partition_get_partno(par),
blkid_partition_get_start(par),
blkid_partition_get_size(par),
blkid_partition_get_type(par));
}

blkid_free_probe(pr);
return 0;

}

C file handling

I am just creating a basic file handling program. the code is this:

#include <stdio.h>
int main()
{
FILE *p;
p=fopen("D:\\TENLINES.TXT","r");
if(p==0)
{
    printf("Error",);

}

fclose(p);
}

This is giving Error, I cannot create files tried reinstalling the compiler and using different locations and names for files but no success. I am using Windows 7 and compiler is Dev C++ version 5

Calling C from C#

I am from electric engineer background, therefore my knownledge is small about C#,DLL,etc.... I want to use c function into a C#. I know there is a couple post about that but I didn't find one that is enough simple.

Currently, I got C function call windows API to read/write on the USB port. First to create a .dll do I need a header file? Because I got the following function decleration function into a header. The examples that I saw on stack overflow and Internet only use a simple .c file, Can I get rid of the header files?

__declspec(dllexport) LMUSB_HANDLE  __stdcall InitializeDevice(unsigned short usVID,
                                    unsigned short usPID,
                                    LPGUID lpGUID,
                                    BOOL *pbDriverInstalled);
__declspec(dllexport) LMUSB_HANDLE  __stdcall InitializeDeviceByIndex(unsigned short usVID,
                                           unsigned short usPID,
                                           LPGUID lpGUID,
                                           DWORD dwIndex,
                                           BOOL bOpenDataEndpoints,
                                           BOOL *pbDriverInstalled);
__declspec(dllexport) BOOL  __stdcall TerminateDevice(LMUSB_HANDLE hHandle);
__declspec(dllexport) BOOL  __stdcall WriteUSBPacket(LMUSB_HANDLE hHandle,
                          unsigned char *pcBuffer,
                          unsigned long ulSize,
                          unsigned long *pulWritten);
__declspec(dllexport) DWORD  __stdcall ReadUSBPacket(LMUSB_HANDLE hHandle,
                         unsigned char *pcBuffer,
                         unsigned long ulSize,
                         unsigned long *pulRead,
                         unsigned long ulTimeoutMs,
                         HANDLE hBreak);
 __declspec(dllexport) BOOL  __stdcall Endpoint0Transfer(LMUSB_HANDLE hHandle, UCHAR ucRequestType,
                             UCHAR ucRequest, USHORT usValue,
                             USHORT usIndex, USHORT usLength,
                             PUCHAR pucBuffer, PUSHORT pusCount);

Second point, do I need to write __declspec(dllexport) in the cpp file? Here an function from the cpp:

extern "C" __declspec(dllexport) BOOL PASCAL EXPORT TerminateDevice(LMUSB_HANDLE hUSB)

I got no idea what "BOOL PASCAL EXPORT" does, this code is recycled from a furnisher project.

Finaly, when the DLL is properly build. How I import it in the C# project? I tried the following but without success :

[DllImport("lmusbdll.dll")]

I see that you could use right click on the project and add reference but Visual Studio pop-up an error message:

A reference to "DLL path" could not be added. Please make sure that the file is accessible, and that it is a valid assembly or COM component.

[EDIT]

I tried the following solution , but when I tried to reference the header file in my c# project. I still get the message that I cannot reference the file.

String permutation - How does this backtracking recursion work?

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

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

Any help is appreciated. Thanks and regards.

Usage of keyword const in a function argument [duplicate]

This question already has an answer here:

Taking the following example:

void foo(const int foobar);

Is the keyword const meaningful?

Difference between Internal terminal, External terminal and Standard output in Netbeans

I just got to know there are multiple consoles in Netbeans when working on a C-program. Please let me know what are the differences between them and when will they be used. Please see the screenshot

enter image description here

Data compare of files is wrong. Why? [on hold]

So, the thing is, this program checks if there are duplicate files in a directory. It uses mostly the windows.h library. To spare code, all the file paths are stored in the buffer finalizedList. The list is always correct, don't worry about it.

To show you the problem, here are the files in the directory:

  • duplicate_delete.exe = The program itself
  • hello.txt = The original text file
  • hello - Copy.txt = A duplicate of "hello.txt". They are exactly the same.
  • hello.cpp = A file that has the exact same name with the original text file, except its extension. (AKA "The Bad Guy")

Now, anytime I run the program while "hello.cpp" is in the directory, this is the output of the program:

Creating list...
Finalizing list...
Starting compare procedure...
Checking: duplicate_delete.exe vs. hello - Copy.txt --> DIFFERENT
Checking: duplicate_delete.exe vs. hello.cpp --> DIFFERENT
Checking: duplicate_delete.exe vs. hello.txt --> DIFFERENT
Checking: hello - Copy.txt vs. hello.cpp --> DIFFERENT
Checking: hello - Copy.txt vs. hello.txt --> DIFFERENT
Checking: hello.cpp vs. hello.txt --> DIFFERENT
Finished.
Press any key to continue . . .

But, when I delete that file the output is this:

Creating list...
Finalizing list...
Starting compare procedure...
Checking: duplicate_delete.exe vs. hello - Copy.txt --> DIFFERENT
Checking: duplicate_delete.exe vs. hello.txt --> DIFFERENT
Checking: hello - Copy.txt vs. hello.txt --> DUPLICATE
Finished.
Press any key to continue . . .

Now... Why does that happen? Or to put it in a better way, how can that happen?

Here are parts of the code:

#include <windows.h>
#include <stdio.h>

HANDLE file1, file2;
const WCHAR * finalizedList[] = { L"duplicate_delete.exe", L"hello - Copy.txt", L"hello.txt", L"hello.cpp" };
WCHAR deleteList[4][1024];
DWORD fileListP, deleteListP;

DWORD openFile1(WCHAR path[1024]);
DWORD openFile2(WCHAR path[1024]);
DWORD compare();
void startCompare();

int main(void)
{
    fileListP = 4;
    printf_s("Starting compare procedure...\n");
    startCompare();
    printf_s("Finished.\n");
    _fcloseall();
    system("pause");

    return 0;
}

DWORD openFile1(WCHAR path[1024])
{
    if ((file1 = CreateFile(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) return 0;
    return 1;
}

DWORD openFile2(WCHAR path[1024])
{
    if ((file2 = CreateFile(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) return 0;
    return 1;
}

DWORD compare()
{
    DWORD a, b;
    BYTE byte1, byte2;

    while (1)
    {
        ReadFile(file1, &byte1, 1, &a, NULL);
        ReadFile(file2, &byte2, 1, &b, NULL);
        if (a != b) return 1;
        if (byte2 != byte1) return 1;
        if (a == 0 && b == 0) break;
    }

    return 0;
}

void startCompare()
{
    WCHAR currentFile[1024], comparedFile[1024];
    DWORD i, j;
    i = 0;

    for (j = 0; j < fileListP; ++j)
    {
        lstrcpy(currentFile, finalizedList[j]);
        if (!openFile1(currentFile)) wprintf(L"File \"%ls\" couldn not be opened for comparing.\n", currentFile);
        else
        {
            for (i = j + 1; i < fileListP; ++i)
            {
                lstrcpy(comparedFile, finalizedList[i]);
                if (!openFile2(comparedFile)) wprintf(L"File \"%ls\" couldn not be compared with file \"%ls\".\n", currentFile, comparedFile);
                else
                {
                    if (!compare())
                    {
                        wprintf(L"Checking: %ls vs. %ls --> DUPLICATE\n", currentFile, comparedFile);
                        lstrcpy(deleteList[deleteListP], currentFile);
                        ++deleteListP;
                    }
                    else
                    {
                        wprintf(L"Checking: %ls vs. %ls --> DIFFERENT\n", currentFile, comparedFile);
                    }
                    CloseHandle(file2);
                }
            }
            CloseHandle(file1);
        }
    }
}

Now... Of course, when I'm to check the program without the hello.cpp file I just delete it from the finalizedList array and make fileListP equal to 3. This is the minimal code that will work.

OpenGL "glGenBuffers' cause segmentation fault

I am not sure what's going on, this was working before and all of a sudden it's just acting really crazy on me.

this is a cmake and sdl project. cmakelists.txt

PROJECT(ren_opengl)

SET(SRC_FILES ren_opengl.c)
set(CMAKE_MACOSX_RPATH 1)

FIND_PACKAGE(SDL2 REQUIRED)
INCLUDE_DIRECTORIES(${SDL2_INCLUDE_DIR})

FIND_PACKAGE(OPENGL REQUIRED)
INCLUDE_DIRECTORIES( ${OPENGL_INCLUDE_DIR})

ADD_EXECUTABLE(ren_opengl ${SRC_FILES})
TARGET_LINK_LIBRARIES(ren_opengl ${SDL2_LIBRARY} ${OPENGL_LIBRARIES})

included headers

#include <SDL2/SDL.h>
#include <OpenGL/gl3.h>
#include <SDL2/SDL_opengl.h>

Init SDL in ren_opengl.c

int init_sdl(int width, int height, char* title, double fps)
{

if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
  {
    SDL_Log("sdl failed to init");
    SDL_Quit();
    return -1;
  }

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);


  window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
  if(window == NULL)
  {
    SDL_Log("sdl failed to create window");
    SDL_Quit();
    return -1;
  }

  maincontext = SDL_GL_CreateContext(window);
  if(maincontext == NULL)
  {
    SDL_Log("sdl failed to create opengl context");
    SDL_Quit();
    return -1;
  }
    SDL_GL_SetSwapInterval(1);


  return 1;

}

at the end of init sdl everything is working, I ca

void render()
{
    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    SDL_GL_SwapWindow(window);
}

if I create a GLuint vao; that causes no problems, as soon as I try to do glGenBuffers(1, &vao); That line above keeps giving segmentation fault.

I even just updated to sdl 2.0.4 but i am really not sure what's going on now.

How to become a good programmer/developer? [on hold]

How to become a good programmer? I didn't choose yet the way (Android or Frontend) but I want to become a true programmer. Should I start from C/Pascal or I can just start to learn Javascript/Java as my first programming language and practice?

Filling a polygon

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

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

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

    int i;

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

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

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

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


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

Why do I get different results when using libiconv over iconv binary?

Here is the sample string that I am using encoded in UCS-2:

abvgdđežzijklmnjoprstćuvhcčdžš1234567890*+;'

When converting UCS-2 to iso ISO-8859-1//TRANSLIT with iconv binary from file to file I get:

abvgd?ezzijklmnjoprstcuvhccdzs1234567890*+;'

Now I want to use libiconv in go project. I am using this library http://ift.tt/1VZ1bwG as bindings for libiconv. But when using bindings I get:

abvgd?e?zijklmnjoprst?uvhc?d??1234567890*+;'

It's like different transliteration rules apply when using library inside go.

I examined go bindings library and everything seems in order; only bytes are passed around so no "loss of information" could happen there.

Is there anything else that I should be aware of when using libiconv? Is there some environment context that could trigger different transliteration behaviour?

Beginner's Query: on C Function return value

I am trying to get some understanding about how pass by value & return are happening in C functions. I cam across a piece of code as follows:

#include <stdio.h>

int fun(int ii, int jj)
{
 int kk, ll;
 kk = ii + jj;
 ll = ii * jj;
 return (kk,ll);
}

int main()
{
 int i=4, j=5, k, l;
 k = fun(i, j);
 l = fun(i, j);
 printf("%d %d\n", k, l);
 return 0;
}

Now apparently I am not getting any errors when I am trying to return 2 values through

fun()

Also, the value that is returned by fun () is "ll" i.e 20 (=4*5) and not "kk". Further, If I rewrite the return statement as :

return (ll,kk);

the value returned is "kk" ie. 9 (=4+5). Query: Why this is so? Thanks!

Is uninitialized local variable the fastest random number generator?

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

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

is it that faster than

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

and also faster than other random number generator?

Undefined symbols for architecture x86_64 on Xcode 6.3

I'am finalising an Open Source C coded CometD library, i thought it would be a good idea to open it to OSX/iOS users, like myself.

In order to ease up the work for OSX/iOS developers i wanted to switch from a static C library to a Xcode iOS Static Libary. So i followed advices found on the net, and generated a static iOS compatible library.

The problem is that, each time i try to use it i get an error of type :

Undefined symbols for architecture x86_64: ******, referenced from: -********** in *******.a(*******.o)

This error get repeated for almost every C function that i have in my library.

First i though maybe the library is not x86_64 compatible, empty, or really doesn't have any x86_64 symbol in it.

So i checked with a "lipo -info" on the library and here is the answer :

enter image description here

To really be sure i also used "nm -arch x86_64" on the library, and went fetching for several undefined functions reported by Xcode as errors. I thought i will be wrong and find nothing but guess what ? I found the symbols : enter image description here

enter image description here

So my question is :

If the symbols are present in a x86_64 compatible library, why is Xcode prompting this error ? Even if i compile the library for all arm*/s types i still get this x86_64 error.

Am i unaware of something or am i just doing it wrong ?

Your answers are always appreciated.

Update (This is the link to the Xcode Project) : http://ift.tt/1IhiEcl

Deadlock or waiting in a loop?

Folks,

I am trying to track why my application stops responding to events.

Some Background: The App in question My_C_Application is a (C application with both C and C++ code) it also referenced a .Net dll which exposes functionality as COM objects, these are register using regasm and the associated tlh is used to resolve these classes to load and use. The app also uses a third party Messaging library IPWorks, we use the SSL version for c++ here and this talks to other systems which are .net based over IP. These other systems use the .Net version of IpWorks, My_C_Application acts as the business logic engine and the other apps handle Data, GUI etc.

This all seems to work fine in testing & in many client sites, in some client sites we are getting reports where the GUI is not responding to an clicks (now we have seen this occur on site, the GUI is hanndling the Key Presses and dispatches its messages approiately) It seems My_C_Application is not handling/ receiving the events.

We caught this issue and using procdump -mp we got a dump to analyze.

I automate this for Crashes with our own application which calls out to the console version of windbg, we execute the following commands for a crash :

!analyze -v; .ecxr;

Now i understand this will be of no use for a hang, so i execute additional commands after this has setup the symbol paths for me etc.

    Opened log file 'C:\crash\AutomateCrashAnalysis\AutomateCrashAnalysis\bin\Debug\CrashSummary1584124051.txt'

    Microsoft (R) Windows Debugger Version 6.12.0002.633 X86
    Copyright (c) Microsoft Corporation. All rights reserved.


    Loading Dump File [C:\Crash\My_C_Application.exe_150804_094908.dmp\My_C_Application.exe_150804_094908.dmp]
    User Mini Dump File: Only registers, stack and portions of memory are available

    Comment: '
    *** procdump.exe -mp 7908
    *** Manual dump'
    Symbol search path is: C:\crash\AutomateCrashAnalysis\AutomateCrashAnalysis\bin\Debug\My_C_Application___Win32_Debug;srv*C:\SYMBOLS*http://ift.tt/1dF6hHm
    Executable search path is: C:\crash\AutomateCrashAnalysis\AutomateCrashAnalysis\bin\Debug\My_C_Application___Win32_Debug
    Windows XP Version 2600 (Service Pack 3) UP Free x86 compatible
    Product: WinNt, suite: SingleUserTS
    Machine Name:
    Debug session time: Tue Aug  4 09:49:13.000 2015 (UTC + 1:00)
    System Uptime: 0 days 14:59:40.140
    Process Uptime: 0 days 3:08:03.000
    ................................................................
    .....................
    eax=00000000 ebx=00128094 ecx=0012804c edx=7c90e514 esi=00000000 edi=7ffd5000
    eip=7c90e514 esp=0012806c ebp=00128108 iopl=0         nv up ei pl zr na pe nc
    cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00200246
    ntdll!KiFastSystemCallRet:
    7c90e514 c3              ret
    0:000> !analyze -v; .ecxr;
    *******************************************************************************
    *                                                                             *
    *                        Exception Analysis                                   *
    *                                                                             *
    *******************************************************************************

    *** WARNING: Unable to verify checksum for mscorlib.ni.dll
    *** WARNING: Unable to verify checksum for System.Windows.Forms.ni.dll
    *** WARNING: Unable to verify checksum for System.ni.dll
    Unable to load image C:\EPOS\ipworksssl9.dll, Win32 error 0n2
    *** ERROR: Symbol file could not be found.  Defaulted to export symbols for ipworksssl9.dll - 
    Unable to load image C:\AppPath\My_C_Application.exe, Win32 error 0n2
    *** WARNING: Unable to verify checksum for My_C_Application.exe
    *** ERROR: Symbol file could not be found.  Defaulted to export symbols for My_C_Application.exe - 
    *** ERROR: Module load completed but symbols could not be loaded for xpsp2res.dll
    GetPageUrlData failed, server returned HTTP status 404
    URL requested: http://ift.tt/1E69hsf

    FAULTING_IP: 
    +1562faf0007da9c
    00000000 ??              ???

    EXCEPTION_RECORD:  ffffffff -- (.exr 0xffffffffffffffff)
    .exr 0xffffffffffffffff
    ExceptionAddress: 00000000
       ExceptionCode: 80000003 (Break instruction exception)
      ExceptionFlags: 00000000
    NumberParameters: 0

    FAULTING_THREAD:  000020f8

    PROCESS_NAME:  My_C_Application.exe

    ERROR_CODE: (NTSTATUS) 0x80000003 - {EXCEPTION}  Breakpoint  A breakpoint has been reached.

    EXCEPTION_CODE: (HRESULT) 0x80000003 (2147483651) - One or more arguments are invalid

    MOD_LIST: <ANALYSIS/>

    NTGLOBALFLAG:  0

    APPLICATION_VERIFIER_FLAGS:  0

    MANAGED_STACK: !dumpstack -EE
    !dumpstack -EE
    No export dumpstack found

    LAST_CONTROL_TRANSFER:  from 7c90df4a to 7c90e514

    ADDITIONAL_DEBUG_TEXT:  Followup set based on attribute [Is_ChosenCrashFollowupThread] from Frame:[0] on thread:[PSEUDO_THREAD]

    DEFAULT_BUCKET_ID:  STACKIMMUNE

    PRIMARY_PROBLEM_CLASS:  STACKIMMUNE

    BUGCHECK_STR:  APPLICATION_FAULT_STACKIMMUNE_NOSOS_WRONG_SYMBOLS

    STACK_TEXT:  
    00000000 00000000 My_C_Application.exe+0x0


    STACK_COMMAND:  .cxr 00000000 ; kb ; ** Pseudo Context ** ; kb

    SYMBOL_NAME:  My_C_Application.exe

    FOLLOWUP_NAME:  MachineOwner

    MODULE_NAME: My_C_Application

    IMAGE_NAME:  My_C_Application.exe

    DEBUG_FLR_IMAGE_TIMESTAMP:  55b8bb1c

    FAILURE_BUCKET_ID:  STACKIMMUNE_80000003_My_C_Application.exe!Unknown

    BUCKET_ID:  APPLICATION_FAULT_STACKIMMUNE_NOSOS_WRONG_SYMBOLS_My_C_Application.exe

    FOLLOWUP_IP: 
    My_C_Application+0
    00400000 4d              dec     ebp

    WATSON_STAGEONE_URL:  http://ift.tt/1SHLRW7

    Followup: MachineOwner
    ---------

    Minidump doesn't have an exception context
    Unable to get exception context, HRESULT 0x80004002
    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

    0:000> .lastevent
    Last event: 1ee4.20f8: Break instruction exception - code 80000003 (first/second chance not available)
      debugger time: Tue Aug  4 12:40:51.455 2015 (UTC + 1:00)

Is there anything of use in the above output that i can use?

Now the code we have is the exact code that is running on site, the EXE was however re-built on another PC for debuging so the symbols dont seem to load, we have seen this before so we execute the following commands:

    0:000> .symopt+0x80000000
    Symbol options are 0x800B0277:
      0x00000001 - SYMOPT_CASE_INSENSITIVE
      0x00000002 - SYMOPT_UNDNAME
      0x00000004 - SYMOPT_DEFERRED_LOADS
      0x00000010 - SYMOPT_LOAD_LINES
      0x00000020 - SYMOPT_OMAP_FIND_NEAREST
      0x00000040 - SYMOPT_LOAD_ANYTHING
      0x00000200 - SYMOPT_FAIL_CRITICAL_ERRORS
      0x00010000 - SYMOPT_AUTO_PUBLICS
      0x00020000 - SYMOPT_NO_IMAGE_SEARCH
      0x00080000 - SYMOPT_NO_PROMPTS
      0x80000000 - SYMOPT_DEBUG
    0:000> .reload -f -i My_C_Application.exe=00400000
    DBGHELP: C:\crash\AutomateCrashAnalysis\AutomateCrashAnalysis\bin\Debug\My_C_Application___Win32_Debug\My_C_Application.exe - OK
    DBGENG:  C:\crash\AutomateCrashAnalysis\AutomateCrashAnalysis\bin\Debug\My_C_Application___Win32_Debug\My_C_Application.exe - Mapped image memory
    DBGHELP: My_C_Application - private symbols & lines 
             c:\crash\automatecrashanalysis\automatecrashanalysis\bin\debug\My_C_Application___win32_debug\My_C_Application.pdb
    0:000> lme
    start    end        module name
    00400000 013ec000   My_C_Application C (private pdb symbols)  c:\crash\automatecrashanalysis\automatecrashanalysis\bin\debug\My_C_Application___win32_debug\My_C_Application.pdb
    790c0000 79bba000   mscorlib_ni C (deferred)             
    7a440000 7abdf000   System_ni C (deferred)             
    7afd0000 7bbaf000   System_Windows_Forms_ni C (deferred)           

Now we should have the symbols loaded correctly, if i execute kv we see the following:

    0:000> kv
    ChildEBP RetAddr  Args to Child              
    00128068 7c90df4a 7c809590 00000002 00128094 ntdll!KiFastSystemCallRet (FPO: [0,0,0])
    0012806c 7c809590 00000002 00128094 00000001 ntdll!ZwWaitForMultipleObjects+0xc (FPO: [5,0,0])
    00128108 7e4195f9 00000002 00128130 00000000 kernel32!WaitForMultipleObjectsEx+0x12c (FPO: [Non-Fpo])
    00128164 7752e78e 00000001 00128464 000003e8 user32!RealMsgWaitForMultipleObjectsEx+0x13e (FPO: [Non-Fpo])
    0012818c 775572af 00128464 000003e8 001281b8 ole32!CCliModalLoop::BlockFn+0x80 (FPO: [Non-Fpo])
    00128200 79fd05fd 00000002 000003e8 00000001 ole32!CoWaitForMultipleHandles+0xcf (FPO: [Non-Fpo])
    00128220 79fd0564 00000000 000003e8 00000001 mscorwks!NT5WaitRoutine+0x51 (FPO: [Non-Fpo])
    0012828c 79fd04c8 00000001 00128464 00000000 mscorwks!MsgWaitHelper+0xa5 (FPO: [Non-Fpo])
    001282ac 79f6915d 00000001 00128464 00000001 mscorwks!Thread::DoAppropriateAptStateWait+0x28 (FPO: [Non-Fpo])
    00128330 79f691f2 00000001 00128464 00000001 mscorwks!Thread::DoAppropriateWaitWorker+0x13c (FPO: [Non-Fpo])
    00128380 79f99d40 00000001 00128464 00000001 mscorwks!Thread::DoAppropriateWait+0x40 (FPO: [Non-Fpo])
    00128484 792b698f 00000000 00000000 03d5bbec mscorwks!WaitHandleNative::CorWaitOneNative+0x156 (FPO: [Non-Fpo])
    001284a0 792b6945 000003e8 00000000 79317b08 mscorlib_ni+0x1f698f
    001284b8 7b6f218f 00000000 00000103 0000c121 mscorlib_ni+0x1f6945
    001284d0 7ba2e34b a92aae2d 79e749d8 00128668 System_Windows_Forms_ni+0x72218f
    00128564 7b6f3aec 00000001 03d5bbd8 03d5bbb8 System_Windows_Forms_ni+0xa5e34b
    001285a0 7b921b1b 03d5bbd8 03d5bbd8 03d5bbb8 System_Windows_Forms_ni+0x723aec
    001285b8 7a932cb6 03d5ac5c 03c2d938 00000001 System_Windows_Forms_ni+0x951b1b
    001285ec 7a930e6f 03d5ac5c ffffffff 00000000 System_ni+0x4f2cb6
    00128638 7a93205f 03d5ac5c 00000009 00000000 System_ni+0x4f0e6f
    00128654 7aaa767a 001fab80 00000001 a92aae2d System_ni+0x4f205f
    001286e4 7e418734 000c00be 0000201a 00000001 System_ni+0x66767a
    00128710 7e418816 030b7392 000c00be 0000201a user32!InternalCallWinProc+0x28
    00128778 7e4189cd 00000000 030b7392 000c00be user32!UserCallWinProcCheckWow+0x150 (FPO: [Non-Fpo])
    001287d8 7e4196c7 00128800 00000001 0012881c user32!DispatchMessageWorker+0x306 (FPO: [Non-Fpo])
    001287e8 1001d222 00128800 00000000 00165008 user32!DispatchMessageA+0xf (FPO: [Non-Fpo])
    WARNING: Stack unwind information not available. Following frames may be wrong.
    0012881c 1007f803 00000014 00040232 100a1e04 ipworksssl9+0x1d222
    001288f4 009d259f 00128924 00e238ae 00000000 ipworksssl9+0x7f803
    00000000 00000000 00000000 00000000 00000000 My_C_Application!sprintf+0x9f (CONV: cdecl) [sprintf.c @ 104]

Does WaitForMultipleObjects indicate a deadlock (waiting for a Lock/CriticalSection/Mutex) ??

I was expecting to see a while loop locked up in My_C_Application but i dont, i ran ~* kp but none of these threads appear to be looping or locked in My_C_Application.

    :000> ~* kp

    .  0  Id: 1ee4.20f8 Suspend: 0 Teb: 7ffdf000 Unfrozen
    ChildEBP RetAddr  
    00128068 7c90df4a ntdll!KiFastSystemCallRet
    0012806c 7c809590 ntdll!ZwWaitForMultipleObjects+0xc
    00128108 7e4195f9 kernel32!WaitForMultipleObjectsEx+0x12c
    00128164 7752e78e user32!RealMsgWaitForMultipleObjectsEx+0x13e
    0012818c 775572af ole32!CCliModalLoop::BlockFn+0x80
    00128200 79fd05fd ole32!CoWaitForMultipleHandles+0xcf
    00128220 79fd0564 mscorwks!NT5WaitRoutine+0x51
    0012828c 79fd04c8 mscorwks!MsgWaitHelper+0xa5
    001282ac 79f6915d mscorwks!Thread::DoAppropriateAptStateWait+0x28
    00128330 79f691f2 mscorwks!Thread::DoAppropriateWaitWorker+0x13c
    00128380 79f99d40 mscorwks!Thread::DoAppropriateWait+0x40
    00128484 792b698f mscorwks!WaitHandleNative::CorWaitOneNative+0x156
    001284a0 792b6945 mscorlib_ni+0x1f698f
    001284b8 7b6f218f mscorlib_ni+0x1f6945
    001284d0 7ba2e34b System_Windows_Forms_ni+0x72218f
    00128564 7b6f3aec System_Windows_Forms_ni+0xa5e34b
    001285a0 7b921b1b System_Windows_Forms_ni+0x723aec
    001285b8 7a932cb6 System_Windows_Forms_ni+0x951b1b
    001285ec 7a930e6f System_ni+0x4f2cb6
    00128638 7a93205f System_ni+0x4f0e6f
    00128654 7aaa767a System_ni+0x4f205f
    001286e4 7e418734 System_ni+0x66767a
    00128710 7e418816 user32!InternalCallWinProc+0x28
    00128778 7e4189cd user32!UserCallWinProcCheckWow+0x150
    001287d8 7e4196c7 user32!DispatchMessageWorker+0x306
    001287e8 1001d222 user32!DispatchMessageA+0xf
    WARNING: Stack unwind information not available. Following frames may be wrong.
    0012881c 1007f803 ipworksssl9+0x1d222
    001288f4 009d259f ipworksssl9+0x7f803
    00000000 00000000 My_C_Application!sprintf(char * string = <Memory access error>, char * format = <Memory access error>)+0x9f [sprintf.c @ 104]

       1  Id: 1ee4.2364 Suspend: 0 Teb: 7ffdd000 Unfrozen
    ChildEBP RetAddr  
    01edfe64 7e4191be ntdll!KiFastSystemCallRet
    01edfe8c 00986a0f user32!NtUserGetMessage+0xc
    01edff80 009867d8 My_C_Application!WMConnection::threadFunc(void)+0x20a [C:\Code\BuildFolder\My_C_Application\SourcePath\WMConnection.cpp @ 139]
    01edffb4 7c80b729 My_C_Application!wmConnectionThreadFunc(void * lpData = 0x01d5b970)+0x62 [C:\Code\BuildFolder\My_C_Application\SourcePath\WMConnection.cpp @ 80]
    01edffec 00000000 kernel32!BaseThreadStart+0x37

       2  Id: 1ee4.204c Suspend: 0 Teb: 7ffdc000 Unfrozen
    ChildEBP RetAddr  
    0214fecc 7c90df4a ntdll!KiFastSystemCallRet
    0214fed0 7c809590 ntdll!ZwWaitForMultipleObjects+0xc
    0214ff6c 7c80a115 kernel32!WaitForMultipleObjectsEx+0x12c
    0214ff88 72d2312a kernel32!WaitForMultipleObjects+0x18
    0214ffb4 7c80b729 wdmaud!MixerCallbackThread+0x42
    0214ffec 00000000 kernel32!BaseThreadStart+0x37

       3  Id: 1ee4.210c Suspend: 0 Teb: 7ffdb000 Unfrozen
    ChildEBP RetAddr  
    0224fd84 7c90df4a ntdll!KiFastSystemCallRet
    0224fd88 7c809590 ntdll!ZwWaitForMultipleObjects+0xc
    0224fe24 7c80a115 kernel32!WaitForMultipleObjectsEx+0x12c
    0224fe40 73f114a2 kernel32!WaitForMultipleObjects+0x18
    0224fe58 73f12862 dsound!WaitObjectArray+0x17
    0224ff78 73f198df dsound!CThread::TpWaitObjectArray+0x51
    0224ff98 73f12896 dsound!CCallbackEventPool::ThreadProc+0x1a
    0224ffa4 73f1b2e9 dsound!CThread::ThreadLoop+0x1d
    0224ffac 73f1b2ae dsound!CThread::PrivateThreadProc+0x32
    0224ffb4 7c80b729 dsound!CThread::ThreadStartRoutine+0xd
    0224ffec 00000000 kernel32!BaseThreadStart+0x37

       4  Id: 1ee4.2344 Suspend: 0 Teb: 7ffda000 Unfrozen
    ChildEBP RetAddr  
    0244fd8c 7c90df4a ntdll!KiFastSystemCallRet
    0244fd90 7c809590 ntdll!ZwWaitForMultipleObjects+0xc
    0244fe2c 7c80a115 kernel32!WaitForMultipleObjectsEx+0x12c
    0244fe48 73f114a2 kernel32!WaitForMultipleObjects+0x18
    0244fe60 73f12862 dsound!WaitObjectArray+0x17
    0244ff80 73f1292b dsound!CThread::TpWaitObjectArray+0x51
    0244ff98 73f12896 dsound!CDirectSoundAdministrator::ThreadProc+0x16
    0244ffa4 73f1b2e9 dsound!CThread::ThreadLoop+0x1d
    0244ffac 73f1b2ae dsound!CThread::PrivateThreadProc+0x32
    0244ffb4 7c80b729 dsound!CThread::ThreadStartRoutine+0xd
    0244ffec 00000000 kernel32!BaseThreadStart+0x37

       5  Id: 1ee4.22d8 Suspend: 0 Teb: 7ffd9000 Unfrozen
    ChildEBP RetAddr  
    0256ff08 7c90df5a ntdll!KiFastSystemCallRet
    0256ff0c 7c8025db ntdll!NtWaitForSingleObject+0xc
    0256ff70 7c802542 kernel32!WaitForSingleObjectEx+0xa8
    0256ff84 5c57ae32 kernel32!WaitForSingleObject+0x12
    0256ffac 5c57bec0 dmime!CPerformance::Realtime+0x127
    0256ffb4 7c80b729 dmime!CPerformance::Release+0x94
    0256ffec 00000000 kernel32!BaseThreadStart+0x37

       6  Id: 1ee4.2190 Suspend: 0 Teb: 7ffd8000 Unfrozen
    ChildEBP RetAddr  
    0266feec 7c90df5a ntdll!KiFastSystemCallRet
    0266fef0 7c8025db ntdll!NtWaitForSingleObject+0xc
    0266ff54 7c802542 kernel32!WaitForSingleObjectEx+0xa8
    0266ff68 5c57effc kernel32!WaitForSingleObject+0x12
    0266ffac 5c57f04d dmime!CPerformance::Transport+0x47d
    0266ffb4 7c80b729 dmime!CPerformance::Transport+0x4ce
    0266ffec 00000000 kernel32!BaseThreadStart+0x37

       7  Id: 1ee4.1dfc Suspend: 0 Teb: 7ffd7000 Unfrozen
    ChildEBP RetAddr  
    029dff10 7c90df5a ntdll!KiFastSystemCallRet
    029dff14 7c8025db ntdll!NtWaitForSingleObject+0xc
    029dff78 7c802542 kernel32!WaitForSingleObjectEx+0xa8
    029dff8c 6c9ae4b5 kernel32!WaitForSingleObject+0x12
    029dffac 6c9ae4ed dmsynth!CDSLinkList::SynthProc+0x95
    029dffb4 7c80b729 dmsynth!CDSLinkList::SynthProc+0xcd
    029dffec 00000000 kernel32!BaseThreadStart+0x37

       8  Id: 1ee4.2778 Suspend: 0 Teb: 7ffd6000 Unfrozen
    ChildEBP RetAddr  
    02adff78 7c90da4a ntdll!KiFastSystemCallRet
    02adff7c 71a5d320 ntdll!NtRemoveIoCompletion+0xc
    02adffb4 7c80b729 mswsock!SockAsyncThread+0x5a
    02adffec 00000000 kernel32!BaseThreadStart+0x37

       9  Id: 1ee4.2188 Suspend: 0 Teb: 7ffd4000 Unfrozen
    ChildEBP RetAddr  
    02eafce8 7c90df4a ntdll!KiFastSystemCallRet
    02eafcec 7c92a51a ntdll!ZwWaitForMultipleObjects+0xc
    02eaffb4 7c80b729 ntdll!RtlpWaitThread+0x13d
    02eaffec 00000000 kernel32!BaseThreadStart+0x37

      10  Id: 1ee4.ee0 Suspend: 0 Teb: 7ffaf000 Unfrozen
    ChildEBP RetAddr  
    02fafec8 7c90df4a ntdll!KiFastSystemCallRet
    02fafecc 7c809590 ntdll!ZwWaitForMultipleObjects+0xc
    02faff68 7c80a115 kernel32!WaitForMultipleObjectsEx+0x12c
    02faff84 769c87bd kernel32!WaitForMultipleObjects+0x18
    02faffb4 7c80b729 userenv!NotificationThread+0x5f
    02faffec 00000000 kernel32!BaseThreadStart+0x37

      11  Id: 1ee4.26b4 Suspend: 0 Teb: 7ffae000 Unfrozen
    ChildEBP RetAddr  
    0333fe38 7c90df4a ntdll!KiFastSystemCallRet
    0333fe3c 7c809590 ntdll!ZwWaitForMultipleObjects+0xc
    0333fed8 7c80a115 kernel32!WaitForMultipleObjectsEx+0x12c
    0333fef4 79f86a21 kernel32!WaitForMultipleObjects+0x18
    0333ff54 79f8697e mscorwks!DebuggerRCThread::MainLoop+0xe9
    0333ff84 79f868a5 mscorwks!DebuggerRCThread::ThreadProc+0xe5
    0333ffb4 7c80b729 mscorwks!DebuggerRCThread::ThreadProcStatic+0x9c
    0333ffec 00000000 kernel32!BaseThreadStart+0x37

      12  Id: 1ee4.bc8 Suspend: 0 Teb: 7ffad000 Unfrozen
    ChildEBP RetAddr  
    034ffcd0 7c90df4a ntdll!KiFastSystemCallRet
    034ffcd4 7c809590 ntdll!ZwWaitForMultipleObjects+0xc
    034ffd70 7c80a115 kernel32!WaitForMultipleObjectsEx+0x12c
    034ffd8c 79fc5107 kernel32!WaitForMultipleObjects+0x18
    034ffdac 79fc9568 mscorwks!WKS::WaitForFinalizerEvent+0x77
    034ffdc0 79e9b08f mscorwks!WKS::GCHeap::FinalizerThreadWorker+0x49
    034ffdd4 79e9b02b mscorwks!Thread::DoADCallBack+0x32a
    034ffe68 79e9af51 mscorwks!Thread::ShouldChangeAbortToUnload+0xe3
    034ffea4 79f73514 mscorwks!Thread::ShouldChangeAbortToUnload+0x30a
    034ffecc 79f73525 mscorwks!ManagedThreadBase_NoADTransition+0x32
    034ffedc 79fc019c mscorwks!ManagedThreadBase::FinalizerBase+0xd
    034fff14 79fc4551 mscorwks!WKS::GCHeap::FinalizerThreadStart+0xbb
    034fffb4 7c80b729 mscorwks!Thread::intermediateThreadProc+0x49
    034fffec 00000000 kernel32!BaseThreadStart+0x37

      13  Id: 1ee4.23b8 Suspend: 0 Teb: 7ffaa000 Unfrozen
    ChildEBP RetAddr  
    03abfee4 7c90df5a ntdll!KiFastSystemCallRet
    03abfee8 7c8025db ntdll!NtWaitForSingleObject+0xc
    03abff4c 7c802542 kernel32!WaitForSingleObjectEx+0xa8
    03abff60 009a6408 kernel32!WaitForSingleObject+0x12
    03abff7c 009dc2d7 My_C_Application!file4writeDelayMain+0x38
    03abffb4 7c80b729 My_C_Application!_threadstart(void * ptd = 0x01d5fa50)+0xa7 [thread.c @ 187]
    03abffec 00000000 kernel32!BaseThreadStart+0x37

      14  Id: 1ee4.fa8 Suspend: 0 Teb: 7ffa9000 Unfrozen
    ChildEBP RetAddr  
    05c6fee4 7c90df5a ntdll!KiFastSystemCallRet
    05c6fee8 7c8025db ntdll!NtWaitForSingleObject+0xc
    05c6ff4c 7c802542 kernel32!WaitForSingleObjectEx+0xa8
    05c6ff60 009a8128 kernel32!WaitForSingleObject+0x12
    05c6ff7c 009dc2d7 My_C_Application!file4advanceReadMain+0x38
    05c6ffb4 7c80b729 My_C_Application!_threadstart(void * ptd = 0x01d5faf8)+0xa7 [thread.c @ 187]
    05c6ffec 00000000 kernel32!BaseThreadStart+0x37

      15  Id: 1ee4.b0 Suspend: 0 Teb: 7ffa8000 Unfrozen
    ChildEBP RetAddr  
    05d6fed4 7c90df5a ntdll!KiFastSystemCallRet
    05d6fed8 7c8025db ntdll!NtWaitForSingleObject+0xc
    05d6ff3c 7c802542 kernel32!WaitForSingleObjectEx+0xa8
    05d6ff50 77596f14 kernel32!WaitForSingleObject+0x12
    05d6ff6c 77567135 ole32!CDllHost::MTAWorkerLoop+0x2b
    05d6ff8c 775263f4 ole32!CDllHost::WorkerThread+0xc1
    05d6ff94 774fe4ba ole32!DLLHostThreadEntry+0xd
    05d6ffa8 774fe522 ole32!CRpcThread::WorkerLoop+0x1e
    05d6ffb4 7c80b729 ole32!CRpcThreadCache::RpcWorkerThreadEntry+0x1b
    05d6ffec 00000000 kernel32!BaseThreadStart+0x37

      16  Id: 1ee4.232c Suspend: 0 Teb: 7ffa5000 Unfrozen
    ChildEBP RetAddr  
    0df8fa74 7c90d21a ntdll!KiFastSystemCallRet
    0df8fa78 7c8023f1 ntdll!NtDelayExecution+0xc
    0df8fad0 7c802455 kernel32!SleepEx+0x61
    0df8fae0 005594cf kernel32!Sleep+0xf
    0df8ff7c 009dc2d7 My_C_Application!Read_FPs_Thread(void * pvoid = 0x00ecb058)+0x888 [C:\Code\BuildFolder\My_C_Application\SourcePath\cbe_pump.cpp @ 2085]
    0df8ffb4 7c80b729 My_C_Application!_threadstart(void * ptd = 0x02fc6018)+0xa7 [thread.c @ 187]
    0df8ffec 00000000 kernel32!BaseThreadStart+0x37

      17  Id: 1ee4.2590 Suspend: 0 Teb: 7ffa7000 Unfrozen
    ChildEBP RetAddr  
    05e6fe14 7c90daaa ntdll!KiFastSystemCallRet
    05e6fe18 77e765e3 ntdll!NtReplyWaitReceivePortEx+0xc
    05e6ff80 77e76caf rpcrt4!LRPC_ADDRESS::ReceiveLotsaCalls+0x12a
    05e6ff88 77e76ad1 rpcrt4!RecvLotsaCallsWrapper+0xd
    05e6ffa8 77e76c97 rpcrt4!BaseCachedThreadRoutine+0x79
    05e6ffb4 7c80b729 rpcrt4!ThreadStartRoutine+0x1a
    05e6ffec 00000000 kernel32!BaseThreadStart+0x37

      18  Id: 1ee4.1b54 Suspend: 0 Teb: 7ffa6000 Unfrozen
    ChildEBP RetAddr  
    0e22fe50 7c90df4a ntdll!KiFastSystemCallRet
    0e22fe54 7c809590 ntdll!ZwWaitForMultipleObjects+0xc
    0e22fef0 7e4195f9 kernel32!WaitForMultipleObjectsEx+0x12c
    0e22ff4c 7e4196a8 user32!RealMsgWaitForMultipleObjectsEx+0x13e
    0e22ff68 4ec674b2 user32!MsgWaitForMultipleObjects+0x1f
    0e22ffb4 7c80b729 GdiPlus!BackgroundThreadProc+0x59
    0e22ffec 00000000 kernel32!BaseThreadStart+0x37

      19  Id: 1ee4.23bc Suspend: 0 Teb: 7ffa4000 Unfrozen
    ChildEBP RetAddr  
    0e84f6d8 7c90d21a ntdll!KiFastSystemCallRet
    0e84f6dc 7c8023f1 ntdll!NtDelayExecution+0xc
    0e84f734 79e889d8 kernel32!SleepEx+0x61
    0e84f768 79f0e0b8 mscorwks!EESleepEx+0xbb
    0e84f778 79f0e0a6 mscorwks!CExecutionEngine::ClrSleepEx+0xe
    0e84f78c 79f0e065 mscorwks!ClrSleepEx+0x14
    0e84f7c8 79f0e166 mscorwks!Thread::UserSleep+0x63
    0e84f868 0e3af62b mscorwks!ThreadNative::Sleep+0xce
    WARNING: Frame IP not in any known module. Following frames may be wrong.
    0e84f8b8 792d7026 0xe3af62b
    0e84f8c4 792e04af mscorlib_ni+0x217026
    0e84f8d8 792d6fa4 mscorlib_ni+0x2204af
    0e84f8f0 79e71b4c mscorlib_ni+0x216fa4
    0e84f900 79e88e45 mscorwks!CallDescrWorker+0x33
    0e84f980 79e96461 mscorwks!CallDescrWorkerWithHandler+0xa3
    0e84fab8 79e96494 mscorwks!MethodDesc::CallDescr+0x19c
    0e84fad4 79e964b2 mscorwks!MethodDesc::CallTargetWorker+0x1f
    0e84faec 79f0f9b7 mscorwks!MethodDescCallSite::CallWithValueTypes_RetArgSlot+0x1a
    0e84fcd4 79e9b08f mscorwks!ThreadNative::KickOffThread_Worker+0x192
    0e84fce8 79e9b02b mscorwks!Thread::DoADCallBack+0x32a
    0e84fd7c 79e9af51 mscorwks!Thread::ShouldChangeAbortToUnload+0xe3
    0e84fdb8 79e9b0dd mscorwks!Thread::ShouldChangeAbortToUnload+0x30a
    0e84fde0 79f0f788 mscorwks!Thread::ShouldChangeAbortToUnload+0x33e
    0e84fdf8 79f0f862 mscorwks!ManagedThreadBase::KickOff+0x13
    0e84fe94 79fc4551 mscorwks!ThreadNative::KickOffThread+0x269
    0e84ffb4 7c80b729 mscorwks!Thread::intermediateThreadProc+0x49
    0e84ffec 00000000 kernel32!BaseThreadStart+0x37

      20  Id: 1ee4.27c8 Suspend: 0 Teb: 7ffa2000 Unfrozen
    ChildEBP RetAddr  
    0eb0fed0 7c90d21a ntdll!KiFastSystemCallRet
    0eb0fed4 7c8023f1 ntdll!NtDelayExecution+0xc
    0eb0ff2c 79ee7c61 kernel32!SleepEx+0x61
    0eb0ffa8 79ee7b0f mscorwks!ThreadpoolMgr::TimerThreadFire+0x6d
    0eb0ffb4 7c80b729 mscorwks!ThreadpoolMgr::TimerThreadStart+0x57
    0eb0ffec 00000000 kernel32!BaseThreadStart+0x37

      21  Id: 1ee4.2710 Suspend: 0 Teb: 7ffa1000 Unfrozen
    ChildEBP RetAddr  
    0e5cff10 7e4191be ntdll!KiFastSystemCallRet
    0e5cff30 7752ffc6 user32!NtUserGetMessage+0xc
    0e5cff70 775264c1 ole32!CDllHost::STAWorkerLoop+0x72
    0e5cff8c 775263f4 ole32!CDllHost::WorkerThread+0xc8
    0e5cff94 774fe4ba ole32!DLLHostThreadEntry+0xd
    0e5cffa8 774fe522 ole32!CRpcThread::WorkerLoop+0x1e
    0e5cffb4 7c80b729 ole32!CRpcThreadCache::RpcWorkerThreadEntry+0x1b
    0e5cffec 00000000 kernel32!BaseThreadStart+0x37

      22  Id: 1ee4.2530 Suspend: 0 Teb: 7ffde000 Unfrozen
    ChildEBP RetAddr  
    01c4fd74 7c90da4a ntdll!KiFastSystemCallRet
    01c4fd78 7c80a7e6 ntdll!NtRemoveIoCompletion+0xc
    01c4fda4 79f65810 kernel32!GetQueuedCompletionStatus+0x29
    01c4fe14 79fc4551 mscorwks!ThreadpoolMgr::CompletionPortThreadStart+0x141
    01c4ffb4 7c80b729 mscorwks!Thread::intermediateThreadProc+0x49
    01c4ffec 00000000 kernel32!BaseThreadStart+0x37

Is there any other commands i can run to figure out where this Lock/Loop is called from in My_C_Application??

Additions:

As requested by EdChum, it would appear from this we are not waiting on any Locks

    0:000> !cs -s -l -o
    -----------------------------------------
    DebugInfo          = 0x0016eea8
    Critical section   = 0x01d59c60 (+0x1D59C60)
    LOCKED
    LockCount          = 0x0
    OwningThread       = 0x000020f8
    RecursionCount     = 0x1
    LockSemaphore      = 0x0
    SpinCount          = 0x00000000
    OwningThread DbgId = ~0s
    OwningThread Stack =
        ChildEBP RetAddr  Args to Child              
        00128068 7c90df4a 7c809590 00000002 00128094 ntdll!KiFastSystemCallRet (FPO: [0,0,0])
        0012806c 7c809590 00000002 00128094 00000001 ntdll!ZwWaitForMultipleObjects+0xc (FPO: [5,0,0])
        00128108 7e4195f9 00000002 00128130 00000000 kernel32!WaitForMultipleObjectsEx+0x12c (FPO: [Non-Fpo])
        00128164 7752e78e 00000001 00128464 000003e8 user32!RealMsgWaitForMultipleObjectsEx+0x13e (FPO: [Non-Fpo])
        0012818c 775572af 00128464 000003e8 001281b8 ole32!CCliModalLoop::BlockFn+0x80 (FPO: [Non-Fpo])
        00128200 79fd05fd 00000002 000003e8 00000001 ole32!CoWaitForMultipleHandles+0xcf (FPO: [Non-Fpo])
        00128220 79fd0564 00000000 000003e8 00000001 mscorwks!NT5WaitRoutine+0x51 (FPO: [Non-Fpo])
        0012828c 79fd04c8 00000001 00128464 00000000 mscorwks!MsgWaitHelper+0xa5 (FPO: [Non-Fpo])
        001282ac 79f6915d 00000001 00128464 00000001 mscorwks!Thread::DoAppropriateAptStateWait+0x28 (FPO: [Non-Fpo])
        00128330 79f691f2 00000001 00128464 00000001 mscorwks!Thread::DoAppropriateWaitWorker+0x13c (FPO: [Non-Fpo])
        00128380 79f99d40 00000001 00128464 00000001 mscorwks!Thread::DoAppropriateWait+0x40 (FPO: [Non-Fpo])
        00128484 792b698f 00000000 00000000 03d5bbec mscorwks!WaitHandleNative::CorWaitOneNative+0x156 (FPO: [Non-Fpo])
        001284a0 792b6945 000003e8 00000000 79317b08 mscorlib_ni+0x1f698f
        001284b8 7b6f218f 00000000 00000103 0000c121 mscorlib_ni+0x1f6945
        001284d0 7ba2e34b a92aae2d 79e749d8 00128668 System_Windows_Forms_ni+0x72218f
        00128564 7b6f3aec 00000001 03d5bbd8 03d5bbb8 System_Windows_Forms_ni+0xa5e34b
        001285a0 7b921b1b 03d5bbd8 03d5bbd8 03d5bbb8 System_Windows_Forms_ni+0x723aec
        001285b8 7a932cb6 03d5ac5c 03c2d938 00000001 System_Windows_Forms_ni+0x951b1b
        001285ec 7a930e6f 03d5ac5c ffffffff 00000000 System_ni+0x4f2cb6
        00128638 7a93205f 03d5ac5c 00000009 00000000 System_ni+0x4f0e6f
    ntdll!RtlpStackTraceDataBase is NULL. Probably the stack traces are not enabled.

Thanks in Advance

Two programs running the same function twice, One can handle it, One can't. Why? C

I'm cross-posting this with the arduino exchange because i'm not sure if it's a problem with my C or something else entirely.

I'm attempting to communicate over wifi using the process library (Part of the arduino yun's librarys) And I'm calling the same functions in the same way in two programs. One program works the other doesn't.

These are the functions:

Process p;    // Create a process and call it "p"
p.begin("curl");  // Process that launch the "curl" command
p.addParameter(b); // Add the URL parameter to "curl"
p.run();    // Run the process and wait for its termination
Console.flush();
Console.println("CurlSetup");
while (p.available() > 0) {
  //Stuff
}

I have successfully called the functions once in my more complicated program but ran into trouble when I tried using the functions twice. I then found the example of using these functions in the IDE and changed it slightly to run the functions twice in the program (to mirror my own program).

My code console printout:

Create String:http://ift.tt/1E69hs4
"102N"
1Nodeid: 102
Nodeid: 102
0
apikey=xxxx
&node=102
&json=0x0201,0x0000,0x019,0x0
http://ift.tt/1SHLUkD
Breaks
Here
http://ift.tt/1SHLUkH
http://ift.tt/1E69hs6
http://ift.tt/1SHLUkJ
CurlSetup

Just to clarify, this should produce a much larger print out. My program just stops and crashes at this point. The print out of a successful run through would be 2-3 times longer than this.

Modified working example printout:

Unable to connect: retrying (1)... 
Unable to connect: retrying (2)... connected!

           `:;;;,`                      .:;;:.           
        .;;;;;;;;;;;`                :;;;;;;;;;;:     TM 
      `;;;;;;;;;;;;;;;`            :;;;;;;;;;;;;;;;      
     :;;;;;;;;;;;;;;;;;;         `;;;;;;;;;;;;;;;;;;     
    ;;;;;;;;;;;;;;;;;;;;;       .;;;;;;;;;;;;;;;;;;;;    
   ;;;;;;;;:`   `;;;;;;;;;     ,;;;;;;;;.`   .;;;;;;;;   
  .;;;;;;,         :;;;;;;;   .;;;;;;;          ;;;;;;;  
  ;;;;;;             ;;;;;;;  ;;;;;;,            ;;;;;;. 
 ,;;;;;               ;;;;;;.;;;;;;`              ;;;;;; 
 ;;;;;.                ;;;;;;;;;;;`      ```       ;;;;;`
 ;;;;;                  ;;;;;;;;;,       ;;;       .;;;;;
`;;;;:                  `;;;;;;;;        ;;;        ;;;;;
,;;;;`    `,,,,,,,,      ;;;;;;;      .,,;;;,,,     ;;;;;
:;;;;`    .;;;;;;;;       ;;;;;,      :;;;;;;;;     ;;;;;
:;;;;`    .;;;;;;;;      `;;;;;;      :;;;;;;;;     ;;;;;
.;;;;.                   ;;;;;;;.        ;;;        ;;;;;
 ;;;;;                  ;;;;;;;;;        ;;;        ;;;;;
 ;;;;;                 .;;;;;;;;;;       ;;;       ;;;;;,
 ;;;;;;               `;;;;;;;;;;;;                ;;;;; 
 `;;;;;,             .;;;;;; ;;;;;;;              ;;;;;; 
  ;;;;;;:           :;;;;;;.  ;;;;;;;            ;;;;;;  
   ;;;;;;;`       .;;;;;;;,    ;;;;;;;;        ;;;;;;;:  
    ;;;;;;;;;:,:;;;;;;;;;:      ;;;;;;;;;;:,;;;;;;;;;;   
    `;;;;;;;;;;;;;;;;;;;.        ;;;;;;;;;;;;;;;;;;;;    
      ;;;;;;;;;;;;;;;;;           :;;;;;;;;;;;;;;;;:     
       ,;;;;;;;;;;;;;,              ;;;;;;;;;;;;;;       
         .;;;;;;;;;`                  ,;;;;;;;;:         




    ;;;   ;;;;;`  ;;;;:  .;;  ;; ,;;;;;, ;;. `;,  ;;;;   
    ;;;   ;;:;;;  ;;;;;; .;;  ;; ,;;;;;: ;;; `;, ;;;:;;  
   ,;:;   ;;  ;;  ;;  ;; .;;  ;;   ,;,   ;;;,`;, ;;  ;;  
   ;; ;:  ;;  ;;  ;;  ;; .;;  ;;   ,;,   ;;;;`;, ;;  ;;. 
   ;: ;;  ;;;;;:  ;;  ;; .;;  ;;   ,;,   ;;`;;;, ;;  ;;` 
  ,;;;;;  ;;`;;   ;;  ;; .;;  ;;   ,;,   ;; ;;;, ;;  ;;  
  ;;  ,;, ;; .;;  ;;;;;:  ;;;;;: ,;;;;;: ;;  ;;, ;;;;;;  
  ;;   ;; ;;  ;;` ;;;;.   `;;;:  ,;;;;;, ;;  ;;,  ;;;;   
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.4.2</center>
</body>
</html>

It also breaks either the arduino or the IDE. After running my code and trying to upload more code to the arduino, I get the following error:

avrdude: verification error, first mismatch at byte 0x0000
         0xff != 0x0c
avrdude: verification error; content mismatch

In the IDE and it refuses to upload the code to the arduino.

My code, Ip's and Apikey's blanked out: http://ift.tt/1E69hsa

Modified arduino example code: http://ift.tt/1SHLUkN

Threads creation in C

void print_hello_world() {
    pid_t pid = getpid();
    printf("Hello world %d\n", pid);
    pthread_exit(0);
}

void main() {
    pthread_t thread;
    pthread_create(&thread, NULL, (void *) &print_hello_world, NULL);
    print_hello_world();
}

I really couldn't understand what is the need of (void *) in pthread_create. And do we need "&print_hello_world" in the same or could drop "&" as I have read somewhere that while passing function pointers we don't need to place "&" before the function name.

Trouble with a switch function menu using structs in C

The program compiles fine however there are a few issues that come up...

  1. The calculations will not print out properly.
  2. After making a selection the menu will run again automatically without asking for input.
  3. Edit employees does not overwrite current employee only adds another to the list.

I am including all my code since I am not sure where the bug is.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//This is a macro intended for use with the emplyName array.
#define SIZE 20 

//This struct has all the varibles that I will be using in my functions
typedef struct person
{
    char emplyName[SIZE];
    float emplyHours;
    float emplyRate;
    float emplyGross;
    float emplyBase;
    float emplyOvrt;
    float emplyTax;
    float emplyNet;
    float emplyTotal;
}input;


void menu(void);

void editEmployees(input* emply);

void print(input* emply);

void employeeInfo(input* emply);

void calculations(input *emply);

int main(void)
{
    struct person payroll[5] = { 0 };
    int choice = 0, currentEmployee = 0;
    calculations(&payroll);
    do
    {
        menu();
        scanf_s("%c", &choice, 1);
        switch (choice){
        case '1':{
            employeeInfo(&payroll[currentEmployee]);
            currentEmployee;
            break;
        }
        case '2':{
            editEmployees(&payroll[currentEmployee]);
            break;
        }
        case '3':{
            print(&payroll[currentEmployee]);
            break;
        }
        case '4':{
            printAll(payroll);
            break;
        }
        case '0':{
            break;
        }
        default:
            printf("Invalid entry\n");
        }
    } while (choice != 5);
        system("pause");

}

void employeeInfo(input *emply)
 {
        printf("Enter employee name.\n");
        scanf_s("%s", &emply->emplyName,SIZE);
        printf("Enter employee hours.\n");
        scanf_s("%f", &emply->emplyHours);
        printf("Enter Hourly rate.\n");
        scanf_s("%f", &emply->emplyRate);
} 



void calculations(input *emply)/*Write a method that calculates the gross, base and overtime pay, pass by reference.*/
{
    if (emply->emplyHours > 40) {
            emply->emplyOvrt = (emply->emplyHours - 40) * (emply->emplyRate * 1.5);
        }
        emply->emplyGross = (((emply->emplyHours)*(emply->emplyRate)) + emply->emplyOvrt);
        emply->emplyBase = (emply->emplyGross) - (emply->emplyOvrt);
        emply->emplyTax = ((emply->emplyGross)*.2);
        emply->emplyNet = (emply->emplyGross) - (emply->emplyTax);
        emply->emplyTotal += emply->emplyGross;



}


void print(input *employees)
{
    int i;
    for (i = 0; i < 5; i++)
    {
        printf("Employee Name:%s\n", employees[i].emplyName);
        printf("Hours Worked:%.2f\n ", employees[i].emplyHours);
        printf("Hourly Rate:%.2f\n", employees[i].emplyRate);
        printf("Gross Pay:%.2f\n", employees[i].emplyGross);
        printf("Base Pay:%.2f\n", employees[i].emplyBase);
        printf("Overtime Pay:%.2f\n", employees[i].emplyOvrt);
        printf("Taxes Paid:%.2f\n", employees[i].emplyTax);
        printf("Net Pay:%.2f\n", employees[i].emplyNet);
    }
    printf("Total paid to all employees : %.2f\n", employees[i].emplyTotal);
}

void printAll(input *emply)
{
    int i;
    for (i = 0; i < 5; i++)
    {
        if (strcmp(emply->emplyName[i], "-1") == 0){ 
            break;
        }
        printf("Employee Name:%s\n", emply[i].emplyName);
        printf("Hours Worked:%.2f\n ", emply[i].emplyHours);
        printf("Hourly Rate:%.2f\n", emply[i].emplyRate);
        printf("Gross Pay:%.2f\n", emply[i].emplyGross);
        printf("Base Pay:%.2f\n", emply[i].emplyBase);
        printf("Overtime Pay:%.2f\n", emply[i].emplyOvrt);
        printf("Taxes Paid:%.2f\n", emply[i].emplyTax);
        printf("Net Pay:%.2f\n", emply[i].emplyNet);
    }
    printf("Total paid to all employees : %.2f\n", emply[i].emplyTotal);
}

void editEmployees(input*emply)
{
    int edit;
    int i;
    printf("which employee would you like to edit?\n");
    for (i = 0; i < 5; i++){
        printf("%d.%s\n", i + 1, emply[i].emplyName);
    }
    scanf_s("%d", &edit);
    employeeInfo(&emply[edit]);
}

void menu(void)
{
        printf("Main Menu\n");
        printf("1. Add Employee\n");
        printf("2. Edit Employee\n");
        printf("3. Print Employee\n");
        printf("4. Print All Employees\n");
        printf("0. exit\n");
}

Hex to int conversion of input data using C program

I am trying to convert a hexadecimal data coming from a port( stored in a buffer) into integer format using C program. Before converting from buffer, I wanted to test my code by giving some input in the program. The following is the program I am using from a online source.

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

int hexToInt(char s[]) {
int hexdigit, i, inhex, n;    
i=0;

if(s[i] == '0') {
    ++i;
    if(s[i] == 'x' || s[i] == 'X'){            
        ++i;
    }
}

n = 0;
inhex = 1;
for(; inhex == 1; ++i) {
    if(s[i] >= '0' && s[i] <= '9') {            
        hexdigit = s[i] - '0';
    } else if(s[i] >= 'a' && s[i] <= 'f') {            
        hexdigit = s[i] - 'a' + 10;
    } else if(s[i] >= 'A' && s[i] <= 'F') {
        hexdigit = s[i] - 'A' + 10;
    } else {
        inhex = 0;
    }

    if(inhex == 1) {
        n = 16 * n + hexdigit;
    }
}

return n;
}

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

char hex[] = "93 BC";
int digit = hexToInt(hex);
printf("The Integer is %d", digit);

return 0;
}

When I run this program it converts one input of Hexadecimal into a integer. But If I had to convert of array of hex input like the below:

00 00 00 05 00 00 00 01 93 BC C0 06 00 00 00 00         ................
00 28 17 00 FC 26 CC 62 00 00 00 07 00 00 00 01         .(...&.b........
00 00 00 D0 00 E3 37 19 00 00 00 1D 00 00 01 00         ......7.........
AB B6 CD 14 00 11 1F 3C 00 00 00 1D 00 00 00 00         .......<........
00 00 00 02 00 00 00 01 00 00 00 90 00 00 00 01         ................
00 00 05 EE 00 00 00 04 00 00 00 80 F0 92 1C 48         ...........�...H
C2 00 00 0E 0C 30 C7 C7 08 00 45 00 05 DC 32 70         .....0....E...2p
40 00 2D 06 41 C8 2D 3A 4A 01 93 BC C8 EC 01 BB         @.-.A.-:J.......
C1 58 C5 8D 53 88 05 72 46 E6 80 10 00 53 DC 34 

Then how I can convert it into corresponding integer values?

An efficient way of reading integers from file

I'd like to read all integers from a file into the one list/array. All numbers are separated by space (one or more) or end line character (one or more). What is the most efficient and/or elegant way of doing this? Functions from c++ library are prohibited.

I did it this way:

/* We assume that 'buffer' is big enaugh */
int i = 0;
while(fscanf(fp, "%d", &buffer[i]) != EOF) {
    ++i;
}

Sample data:

1   2     3
 4 56
    789         
9          91 56   

 10 
11

Compile IPerf 2.0.5 source for Android 5.0.2 with Position Independent compilation method

How can I compile IPerf 2.0.5 to generate Position Independent Executable for Android Lollipop 5.0? Can you also share more details on where to add compiler flags in make file of iperf 2.0.5 source code.

The Iperf Source code is found here.

How to increase the potential value of an variable in a 16 bit machine using C

I have created a binary to decimal converter but even small numbers written in binary have many digits and thus are too large to be held by an integer variable on a 16 bit machine. Is there any way around this. The program is in C. Here is the code, thanks:

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

void main()
{
 clrscr();
 int a,b,d=0,x=1;
 int check(int y);
 printf("Enter your number in Binary:");
 scanf("%d",&a);
 if(check(a)==0)
 {
  printf("Number tolerable. Conversion Process Initiated.");
 }
 else 
 {
  printf("Number not binary. Try again.");
  exit(1);
 }

 while(a!=0)
 {
   if(a%10==1)
    {
     d=d+x;
    }
   a=a/10;
   x=x*2;
 }
 printf("\nDecimal:%d",d);
 getch();
}

int check(int y)
{
  while(y!=0)
  {
   if(y%10!=0&&y%10!=1)
   {
    return 1;
   }
   else
   {
    y=y/10;
   }
  }
 return 0;
}

Java implementation in C (maybe platform-specific)

I've had a look at Ruby's implementation in C to learn more about it's object model and the way it implements object-oriented programming. I'd like to find something similar for Java. I understand that Java works very differently with the translation to bytecodes, the JVM and all the stuff.

Is there a source code (maybe in C) from which I can learn OOP concepts in Java (maybe for a particular implementation)? (I'm very interested for instance in how that implementation manages inheritance which is not specified by the standard)

Visual Studio 2015: C++ decorations despite extern "C"

I'm trying to use an SDK from that I have a H and OBJ file. The H file declares all functions as extern "C", yet while linking, I get "Can't resolve external symbol _ibclr@4". The function is called ibclr and takes a 4B-parameter, so it looks like that's just the C++ decoration. But how is extern "C" not working?

How to determine the starting byte of http header in a raw packet?

I am developing a networking application in C. I have the fields and starting byte of the ethernet header, IPV4 header and TCP header. How to get the starting byte (pointer) to the HTTP header?

Can I declare an array first and give its value later?

I tried doing this but got an error. Why can't I do this?

int main()
{
char sweet[5];
sweet = "kova";
printf("My favorite sweet is %s\n", sweet);

return 0;
}

How to replace letters in a string with specific integer values?

I have a wriiten a C program that contains a char array 'long_string' that looks something like this.

 long_string[16] = "AHDAHDAHDAHDAHDA";

I wish to replace the letters in the string as follows: A-0, H-1, D-2.

Could somebody tell me how could I achieve this? I tried to look online but most of the cases show the conversion of letters to there ASCII values which is not what I need. THank you for your time in advance :)

Why am I getting 'Floating point exception: 8'

I'm trying to calculate all the prime numbers from 0 - 100 and I'm getting a floating point exception, could anyone tell me why? (If it helps I'm using gcc)

#include <stdio.h>

int main(void)
{
  int nums[100], i;

  for(i=0;i<100;i++)
    nums[i] = i;

  int j,k,l,z;

  for(i=1;i<100;i++)
    for(j=2;j<100;j++)
      if((nums[i] % nums[j]) == 0)
       {
        nums[j] = 0;
       }

  for(i=0;i<100;i++)
    if(nums[i] != 0)
      break;

  for(z=0;z<100;z++)
    {  
      for(k=i;k<100;k++)
       for(l = (k+2);l < 100;l++)
         if((nums[k] % nums[l]) == 0)
           nums[k] = 0;
    }

  for(i=0;i<100;i++)
    if(nums[i] != 0)
      printf("%d,",nums[i]);

  printf("\n");

  return 0;
}

Using 'scanf', what is the difference between having a variable or pointer in the second argument?

What is the difference between having a variable or pointer in the second argument of scanf.

For example:

scanf("%f",&r);

vs

scanf("%f",r);

Eclipse error when trying to run C code

I'm trying to understand binary and hexadecimal numbers. I want to know why my program won't launch in eclipse. It gives me this error:

launch has encountered a problem

It was running when i used int. My computer is 64bit. I'm trying to understand hardware. I need to know what I'm doing wrong. What can I improve on? Is it okay to declare buffer as a global variable? Thanks.

My code is here.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * convertBase(unsigned long int numberToConvert, long int base)
{

    char buffer[65];
    char *pConvertedNumber;
    char allValues[] = "0123456789abcdef";

    pConvertedNumber = &buffer[sizeof(buffer)-1];

    *pConvertedNumber = '\0';

    do {

        int value = numberToConvert % base;

        pConvertedNumber = pConvertedNumber - 1;

        *pConvertedNumber = allValues[value];

        numberToConvert /= base;

    } while(numberToConvert != 0);

    printf("%s", pConvertedNumber);

    return pConvertedNumber;
}

int main(void){

    unsigned long int numberOne = 1000000000;
    printf("\n%ld in Base 16 = ", numberOne);
    convertBase(numberOne, 16);

    printf("\n");

return 0;
}

Only first frame showed in RTSP Streaming with libvlc

I want to get video of an IP camera and stream it to another IP by libVLC. I write these codes based on examples of libvlc docs. The video streamed successfully and video showed without any problem in destination.But in my display, only first frame was shown. After some search I guessed this problem will be solve by adding RTP over TCP option. But after this change my problem didn't solve yet.

I use Microsoft visual C++ and my codes are:

#include <stdio.h>
 #include <stdlib.h>
 #include <vlc/vlc.h>
#include <Windows.h>
 int main(int argc, char* argv[])
 {
     libvlc_instance_t * inst;
     libvlc_media_player_t *mp;
     libvlc_media_t *m;


     char *myarg0 = "--sout=#transcode{vcodec=h264,scale=Auto,acodec=mpga,ab=128,channels=2,samplerate=44100}:duplicate{dst=display,dst=rtp{sdp=http://rtspdestinationIP:Port}}";
     char *myarg1="--rtsp-tcp"; 
     char *myargs[2] = {myarg1, myarg0};
     /* Load the VLC engine */
     inst = libvlc_new (2, myargs);

     /* Create a new item */
     char *input="http://user:pass@CameraIP//axis-cgi//mjpg//video.cgi";
     m = libvlc_media_new_location (inst,input ); 

     /* Create a media player playing environement */
     mp = libvlc_media_player_new_from_media (m);

     /* No need to keep the media now */
     libvlc_media_release (m);


     /* play the media_player */
     libvlc_media_player_play (mp);

     Sleep (10000000); /* Let it play a bit */

     /* Stop playing */
     libvlc_media_player_stop (mp);

     /* Free the media_player */
     libvlc_media_player_release (mp);

     libvlc_release (inst);

     return 0;
 }

Passin a pointer to a pthread function result in losing his structure

I'm trying to start a thread and giving to him a pointer to a structure. But the pointer received by the function isn't correct. I've got a piece of the structure correct but others aren't.

This is the function where the thread is started :

void start_pointer(struct fsm_pointer *pointer) {
    if ( pointer->started != 0 ){
        printf("CRITICAL : A pointer must be started only once");
        return;
    }
    pthread_create(&pointer->thread, NULL, &pointer_loop, (void *)pointer);
    pointer->started = 1;
}

And here the pointer_loop function :

void *pointer_loop(void * _pointer) {
    struct fsm_pointer * pointer = _pointer; // cast void pointer
    struct fsm_context init_context = {
        .event = event,
        .fnct_args = step.args,
    };
    // call pointer structure member => SEGFAULT
    pointer->current_step.fnct(&init_context); 
    return NULL;
}

The structures are defined as bellow :

struct fsm_pointer{
    pthread_t thread;
    pthread_mutex_t mutex_event;
    pthread_cond_t cond_event;
    struct fsm_event input_event;
    struct fsm_step current_step;
    unsigned short started;
};

struct fsm_step{
    void (*fnct)(const struct fsm_context *);
    void * args;
    struct fsm_trans transition;
};

::EDIT::
Here is where the pointer and step structures come to life :

struct fsm_pointer * create_pointer(struct fsm_step first_step)
{
    struct fsm_pointer *pointer = malloc(sizeof(pointer));
    pointer->thread = 0;
    pointer->mutex_event = PTHREAD_MUTEX_INITIALIZER;
    pointer->cond_event = PTHREAD_COND_INITIALIZER;
    pointer->input_event = _NONE_EVENT;
    pointer->current_step = first_step;
    pointer->started = 0;
    return pointer;
}

struct fsm_step create_step(void (*fnct)(const struct fsm_context *), void *args)
{
    struct fsm_step result = {
            .fnct = fnct,
            .args = args,
            .transition = TRANS_ENDPOINT,
    };
    return result;
}

And here is the function which manage it :

void test_new_fsm(){
    struct fsm_step step_0 = create_step(&callback, NULL);
    struct fsm_pointer *fsm = create_pointer(step_0);

    start_pointer(fsm);
    sleep(5);
    pthread_join(fsm->thread, NULL);
    sleep(1);
    free(fsm);
}

And the callback function is just for the test :

void callback(const struct fsm_context *context) {
    printf("Callback : event uid : %d \n", context->event.uid);
}

::/EDIT::

When I use a debugger (gdb) just before the segfault I can see that the pointer's address is correct (the same as before the thread creation) and that the started variable is correctly set to 1. But the fnct pointer is NULL which produce a segfault.

When the exact same code (with correct variable names) as in the pointer_loop one is executed before the thread creation, there isn't any problem.

So, does someone know what happens, or it's just an obvious mistake which is so obvious that more than a day of debugging isn't enough ?

Thanks.

C - Array containing Linked Lists

I think this question got answered in many ways now, but I am still confused and I am doing strange things with the pointers, so I would really appreciate your help. I want to create an array (unknown size) which contains linked lists. I think the main problems are my use of pointers in this context. Please take a look:

int x_format;
int y_format;
typedef struct{
    int id;
    struct item_node *next;
    union{
        struct{
            int freq
        } Sound;
        struct{
            float reduce;
        } Obstacle;
    } data;
}item_node;
item_node *buffer;
item_node **room;
item_node **room_new;

void createRoom(int x, int y)
{
    buffer = malloc(sizeof(item_node)*x*y);
    room = malloc(sizeof(item_node *)*y);
    for(int i = 0; i<y; i++)
    room[i] = &buffer[i*x];
    for(int j = 0; j<x; ++j)
    {
        for(int k = 0; k<y; ++k)
        {
             room[j][k].next = NULL;
        }
    }
}
item_node createItem (int x, int y, int id)
{
    item_node selected = room[x][y];
    //Error
    if(selected == NULL)
        selected = malloc(sizeof(item_node));
    else{
        while(selected->next != NULL)
            selected = selected->next;

        selected->next = malloc(sizeof(item_node));
        selected = selected->next;
    }

    selected->id = id; 
    selected->next = NULL;
    return selected;
}
int main (int argc, char *argv[])
{
    x_format = 100;
    y_format = 100;

    createRoom(x_format,y_format);
    item_node itemtest = createItem(1,1,0);
    free(room);
    free(buffer);
}

So the problem that occurs is:

error: invalid operands to binary expression ('item_node' and 'void *') if(selected == NULL)

I understand the error but I don't now how to fix that. Sorry if this question is way to trivial and I appreciate any help! Thank you.

Filling a polygon

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

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

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

    int i;

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

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

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

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


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