smallseo.info

c# interview questions

Top c# frequently asked interview questions

Change I2C address Linux driver kernel

I have a system which uses module Sensors LM75 with two I2C adresses (0x48 and 0x49). I'd like to cancel one address (0x48), however I don't understand where there is its initialisation.

All changes in normal_i2c , are not relevant ....

/* Addresses scanned */
static const unsigned short normal_i2c[] = { 0x48, 0x49, 0x4a, 0x4b, 0x4c,
                    0x4d, 0x4e, 0x4f, I2C_CLIENT_END };

Source: (StackOverflow)

mongoLab C driver authentication and Basic Example

I am trying to interface Official C driver with mongoLab but getting error that failed to authenticate credentials. Do anyone have any simple example on how to interface mongolab using C driver. This is my example code

const char* String_uri = "mongodb://<username>:<pwd>@ds011115.mongolab.com:11115/tempdb";

    uri = mongoc_uri_new(String_uri);
    client = mongoc_client_new_from_uri (uri);


   collection = mongoc_client_get_collection (client, "mydb", "mycoll");
   doc = bson_new_from_json ((const uint8_t *)"{\"hello\" : \"world\"}", -1, &error);

   count = mongoc_collection_count (collection, MONGOC_QUERY_NONE, doc, 0, 0, NULL, &error);

   if (count < 0) {
      fprintf (stderr, "%s\n", error.message);
   } else {
      printf ("%" PRId64 "\n", count);
   }

Source: (StackOverflow)

Redirecting shell from client to server via sockets using dup2 without netcat

Does anybody have any ideas on: How I could implement a server for this client without using netcat?

I've tried different things but as I'm not too familiar with pipes I thought about making this post. If I use this code and i set up a netcat listener such as "nc -l 1234" I would receive the redirected shell from the client below.

How could I implement a server with the same functionality without using netcat?

Thanks.

#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main(void) {
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in serv_addr = {0};
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(1234);
    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
    dup2(sock, 0);
    dup2(sock, 1);
    dup2(sock, 2);
    //system("uname -a; w; id");
    execl("/bin/sh", "sh", NULL);
}

Source: (StackOverflow)

Why are my ASCII integer values becoming negative?

I am trying to do a very basic form of encryption and decryption by using operations on ASCII characters in C. I have the following code:

char* myEncrypt(char* stringToEncrypt)
{
    char *encryptedString = malloc(256);
    strcpy(encryptedString, stringToEncrypt);

    int publicKey = 50;

    for (int i = 0; encryptedString[i] && encryptedString[i] != '\n'; ++i)
            encryptedString[i] = (encryptedString[i] + publicKey) % 256;

    return encryptedString;
}

My issue is that when I run this code I am every so often getting negative values for my integer values of the ASCII characters assigned to encryptedString[i]. This is causing the decryption to fail. Looking at the code there should be no way for me to get negative values since I am using the modulo operation. Am I missing something simple here?


Source: (StackOverflow)

Read scientific notation scanf

I am developing a program which should have only one scanf function and it should be able to accept input in scientific notation and real numbers.

Any help will be appreciated


Source: (StackOverflow)

I want a c programme that asks the user to input some n number of strings and the output should be the n strings

Iam getting an error that executable stopped working.Please help me .It is very important for me.


Source: (StackOverflow)

Can the stringize macro be used here?

Using Pelles C I would like to show or log an unsigned char array. Is it possible to use the stringize macro to show the whole array as hex values instead of iterating through the array with printf(%x)?


Source: (StackOverflow)

Pointer Declaration Equivalency

char *charPtr = malloc(50);

char *charPtr; *charPtr = malloc(50);

I have been creating pointers in C like the examples above. Is it okay to say that these two are the same in C?


Source: (StackOverflow)

Have an Issue with c program execution

I'm not sure what issue I am having when executing this code Outputs error "/usr/lib/gcc/x86_64-redhat-linux/4.9.2/../../../../lib64/crt1.o: In function _start':
(.text+0x20): undefined reference to
main'
collect2: error: ld returned 1 exit status"
Here is the code

#include <stdio.h>
int get_input(void);
int is_valid(int);
void print_pattern(int);
int main(void);
/* asks the user for an odd integer between 1 and 9
 * stores the integer
 * returns the number input by the user no matter if it fits the perameters    or not
 */

int get_input(void){
int n;
do{
printf("Enter and odd number less than or equal to 9 and greater than 0 >");
scanf("%d", &n);
}
while(is_valid(n) == 0);
return n;
}
/*
* checks to see if the integer entered by the user is even 
* and checks to see if the number is greater than 0 and less than 10
*/
int is_valid(int x){
if (x==1 || x==3 || x==5 || x==7 || x==9){
return 1;
}
else{
if(x<1){
printf("You have entered a number less than 1. Please try agian."); 
return 0;
}
if(x>9){
printf("You have entered a number greater than 9. Please try agin.");
return 0;
}
else{
printf("You have entered an even number. Please try agian.");
return 0;
}
} 

void print_pattern(int n){
int c, i, space, q, b, l, j;
space = n-1;

 for(i=1; i <= n; ++i){
 for(c=1; c <= space; ++c)
 printf(" ");
 space--;
 for(q=1; q <= 2*i-1; ++q)
 printf("%d", q);
 printf("\n");
 }

 space=1; 
 for(b=1; b <= n-1; ++b){
  for (l=1; l <= space; l++)
 printf(" ");
 space++;
 for(j=1; j <= 2*(n-b)-1; ++j)
 printf("%d", j);
 printf("\n");
 }
 }
 int main(void){
 int z = get_input();
 print_pattern(z);
 return 0;
 }}

Source: (StackOverflow)

How to randomize lowest bits in a 64 bit pattern

I am interested in learning more about the concepts behind bit shifting and the manipulation of randomly generated bits. Below is some code that prints 20 random 64 bit patterns. "rand_bits" uses the C standard rand() to return a 64 bit pattern with all zeros except for the lowest bits, which are randomized. The number of low randomized bits is provided by the only parameter to the function.

   const int LINE_CNT = 20;

    void print_bin(uint64_t num, unsigned int bit_cnt);

    uint64_t rand_bits(unsigned int bit_cnt);

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

        int i;

        srand(time(NULL));
        for(i = 0; i < LINE_CNT; i++) {
            uint64_t val64 = rand_bits(64);
            print_bin(val64, 64);
        }
    return EXIT_SUCCESS;
    }


    void print_bin(uint64_t num, unsigned int bit_cnt) {

        int top_bit_cnt;

        if(bit_cnt <= 0) return;
        if(bit_cnt > 64) bit_cnt = 64;

        top_bit_cnt = 64;
        while(top_bit_cnt > bit_cnt) {
            top_bit_cnt--;
            printf(" ");
        }

        while(bit_cnt > 0) {
            bit_cnt--;
            printf("%d", (num & ((uint64_t)1 << bit_cnt)) != 0);
        }
        printf("\n");

        return;
    }


    /*
     * Name: rand_bits
     * Function: Returns a 64 bit pattern with all zeros except for the
     *           lowest requested bits, which are randomized.  
     * Parameter, "bit_cnt":  How many of the lowest bits, including the
     *           lowest order bit (bit 0) to be randomized
     * Return: A 64 bit pattern with the low bit_cnt bits randomized.
     */
    uint64_t rand_bits(unsigned int bit_cnt) {


        printf("int bit_cnt:", bit_cnt);
        uint64_t result = rand();
        uint64_t result_1 = result>>5;
// uint64_t result_1 = result>>7;

//return result;
        return result_1;

    }

For example, if the function is called with 24 as the argument value, it might return a 64 bit pattern, such as:

0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_​1101_0110_0101_1110_0111_1100

Currently the function rand_bits may show more than 15 random bits coming from the rand() function, but this is by NO means guaranteed.

I thought that to get the 40 bits like in the example I could right shift the bits, but that does not seem to be the concept. Does this require a bit mask of the higher order bits or a mod calculation on the random number generator?

Any suggestions of how to return a bit pattern of all zeros with its lowest bits (bit_cnt) randomized?


Source: (StackOverflow)

I was given this to do in c. someone help me? [on hold]

This is how the question is:

Description: RAM on a computer is a finite resource. Sometimes we simply don’t have enough to perform the calculations we wish to perform. Just as user input might be mal-formed and can cause programs to crash, requesting more RAM than is available will also cause our programs to crash.

General Requirements:

Write a program that starts with a variable holding the value 1 million and iteratively tries to allocate an array of integers of that size.

Increase the size by one million each time through the loop.

At each iteration check to see if the allocation was successful.

Remember to deallocate the memory within the loop before proceeding to the next iteration.

Report the biggest successful allocation to the user.

Note: determine beforehand if a 32bit integer is big enough to hold the array size? If not, what type of variable can you use?

Monitor the memory usage in your task manager as your program runs.

What do you see happening? What would happen to other programs if your program never de-allocated its memory?

Does your reported memory size for the largest allocation make sense given the total amount of RAM on your machine? Are you using a properly sized integer for the allocation size given the total RAM on your machine?


Source: (StackOverflow)

Pass to Value in C math

I am just learning C. i am working through this problem trying to predict the output:

#include <stdio.h>

int gNumber;
int MultiplyIt( int myVar );

int main (int argc, const char * argv[])
{
    int i; gNumber = 2;
    for ( i = 1; i <= 2; i++ )
        gNumber *= MultiplyIt( gNumber );
    printf( "Final value is %d.\n", gNumber );
    return 0;
}

int MultiplyIt( int myVar )
{
    return( myVar * gNumber );
}

so if you run this, the output is 512. i am a bit confused on how the calculation is getting from the initial value of 2, then first time through the 'for' loop it then assigns gNumber = 8. then jumps to 512...

maybe i am missing something easy here, but as i said, i am very new to C and programing in general..


Source: (StackOverflow)

Connection refused on wpa_ctrl_open

I am trying to use C code to access wpa_supplicant in an ARM embedded system running linux. After searching, I realise that I could use wpa_supplicant control interface. I try to open a connection using wpa_ctrl_open(), and resulted in "Connection refused" error:

Failed to connect to wpa_supplicant global interface: /var/run/wpa_supplicant error: Connection refused

The code I am using to test:

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/sockios.h>
#include <netinet/if_ether.h>
#include <net/if.h>
#include <sys/socket.h>
#include <sys/un.h>
#include "includes.h"

#ifdef CONFIG_CTRL_IFACE_UNIX
#include <dirent.h>
#endif /* CONFIG_CTRL_IFACE_UNIX */
#include "wpa_ctrl.h"
#include "common.h"

struct wpa_ctrl {
    int s;
#ifdef CONFIG_CTRL_IFACE_UDP
    struct sockaddr_in local;
    struct sockaddr_in dest;
#else // CONFIG_CTRL_IFACE_UDP
    struct sockaddr_un local;
    struct sockaddr_un dest;
#endif // CONFIG_CTRL_IFACE_UDP
};

static struct wpa_ctrl *ctrl_conn;

int main(int argc,char **argv)
{
    const char *global = "/var/run/wpa_supplicant";
    ctrl_conn = wpa_ctrl_open(global);
    if (ctrl_conn == NULL)
    {
        fprintf(stderr, "Failed to connect to wpa_supplicant "
            "global interface: %s error: %s\n",global,strerror(errno));
        return -1;
    }
    else
    {
        printf("Success\n");
    }
    return 0;
}

After tracing the code in wpa_ctrl.c, I found the problem is on the following IF condition, inside wpa_ctrl_open2() function:

if (connect(ctrl->s, (struct sockaddr *) &ctrl->dest,sizeof(ctrl->dest)) < 0)

I do not know what is the problem and how I can solve it.

On the same machine, I tried to run wpa_cli and it can access wpa_supplicant perfectly.

I used the following command to compile:

gcc -o test_wpa main.c wpa_ctrl.c os_unix.c -DCONFIG_BACKEND_FILE -DCONFIG_IEEE80211W -DCONFIG_DRIVER_WEXT -DCONFIG_WIRELESS_EXTENSION -DCONFIG_DRIVER_NL80211 -DCONFIG_LIBNL20 -DEAP_PSK -DIEEE8021X_EAPOL -DCONFIG_SHA256 -DCONFIG_CTRL_IFACE -DCONFIG_CTRL_IFACE_UNIX -DCONFIG_SME -lrt

wpa_supplicant code (including wpa_ctrl.c & os_unix.c) can be download at here: http://w1.fi/releases/wpa_supplicant-2.5.tar.gz

Many thanks in advance!


Source: (StackOverflow)

Rapidjson seg fault with g++ optimization

I am using Rapidjson and have noticed that when I turn on optimization in g++ (-O1/-O2/-O3) I am getting a segmentation fault. I think I have tracked it down to the GenericValue& AddMember() function within rapidjson.

GenericValue& AddMember(GenericValue& name, GenericValue& value, Allocator& allocator) {
    RAPIDJSON_ASSERT(IsObject());
    RAPIDJSON_ASSERT(name.IsString());

    Object& o = data_.o;
    if (o.size >= o.capacity) {
        if (o.capacity == 0) {
            o.capacity = kDefaultObjectCapacity;
            o.members = reinterpret_cast<Member*>(allocator.Malloc(o.capacity * sizeof(Member)));
        }
        else {
            SizeType oldCapacity = o.capacity;
            o.capacity += (oldCapacity + 1) / 2; // grow by factor 1.5
            o.members = reinterpret_cast<Member*>(allocator.Realloc(o.members, oldCapacity * sizeof(Member), o.capacity * sizeof(Member)));
        }
    }
    o.members[o.size].name.RawAssign(name);
    o.members[o.size].value.RawAssign(value);
    o.size++;
    return *this;
}

When debugging, I can see that kDefaultObjectCapacity ( is being optimized out (this is a static const SizeType kDefaultObjectCapacity = 16)

Therefore the line "o.capacity = kDefaultObjectCapacity;" is not being executed, and the malloc is mallocing 0 bytes then trying to cast it.

Why is this static const being removed?

I have tried making Object& o both volatile and static, neither worked. Any ideas?

Thanks Will

EDIT: I can't easily run the tests as it's on an embedded platform, rapidjson is built using buildroot at the moment. I tried the unit tests but couldn't get them going on the target.

I can have a look at providing the assembly, but it's part of a big application so it might be difficult finding the right bit.

For info, this is the method that calls the rapidjson code and this is where the problem seems to be:

int16_t FrontEndJSONHandlers::get_run_cfg_packer(JSONEngine& json_engine, char *message, int32_t *length)
{
Document doc;

// Need to pack an empty request to get the data
doc.SetObject();
doc.AddMember(JSONRPC_MEMBER, JSONRPC_VERSION, doc.GetAllocator());
doc.AddMember(METHOD_MEMBER, JSON_RPC_METH_GET_RUN_CFG, doc.GetAllocator());
doc.AddMember(ID_MEMBER, json_engine.GetNextMessageID(), doc.GetAllocator());

// Format the message
json_engine.FormatMessageAndRegisterResponseHandler(&doc, &message, &length, get_run_cfg_handler);

return 0;
}

If I make Document doc static, it doesn't seg fault - not sure whether this is the best way around it though?


Source: (StackOverflow)

Pass mach port to child process

I'm trying to pass a mach port to a child process created with fork on Mac OSX. I saw this SO question Sharing Mach ports with child processes but it doesn't have a solution it just describes the problem. Looking at this site https://robert.sesek.com/2014/1/changes_to_xnu_mach_ipc.html it contains directions on passing mach ports to a child process but their is no example code unfortunately.

I tried implementing the port swap but the child process can't receive the message that was sent by the parent process, mach_msg inside of recv_port fails with invalid name. Below is what I have so far. Sorry for so much code, mach IPC kind of makes it hard to be brief.

So how do I pass a mach port to a child process on Mac OSX now that the bootstrap port hack no longer works?

Edit

I changed the code example to reflect the points that Ken Thomases made in his answer, the child process creates a port with a send right and sends it to the parent. However the parent process can't receive the port created and sent by the child and just hangs on recv_port.

#include <stdio.h>
#include <mach/mach.h>
#include <mach/error.h>
#include <mach/message.h>
#include <unistd.h>

static int32_t
send_port(mach_port_t remote_port, mach_port_t port)
{
    kern_return_t err;

    struct
    {
        mach_msg_header_t          header;
        mach_msg_body_t            body;
        mach_msg_port_descriptor_t task_port;
    } msg;

    msg.header.msgh_remote_port = remote_port;
    msg.header.msgh_local_port = MACH_PORT_NULL;
    msg.header.msgh_bits = MACH_MSGH_BITS (MACH_MSG_TYPE_COPY_SEND, 0) |
        MACH_MSGH_BITS_COMPLEX;
    msg.header.msgh_size = sizeof msg;

    msg.body.msgh_descriptor_count = 1;
    msg.task_port.name = port;
    msg.task_port.disposition = MACH_MSG_TYPE_COPY_SEND;
    msg.task_port.type = MACH_MSG_PORT_DESCRIPTOR;

    err = mach_msg_send(&msg.header);
    if(err != KERN_SUCCESS)
    {
        mach_error("Can't send mach msg\n", err);
        return (-1);
    }

    return (0);
}

static int32_t
recv_port(mach_port_t recv_port, mach_port_t *port)
{
    kern_return_t err;
    struct
    {
        mach_msg_header_t          header;
        mach_msg_body_t            body;
        mach_msg_port_descriptor_t task_port;
        mach_msg_trailer_t         trailer;
    } msg;

    err = mach_msg(&msg.header, MACH_RCV_MSG,
                    0, sizeof msg, recv_port,
                    MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
    if(err != KERN_SUCCESS)
    {
        mach_error("Can't recieve mach message\n", err);
        return (-1);
    }

    *port = msg.task_port.name;
    return 0;
}

static int32_t
setup_recv_port(mach_port_t *recv_port)
{
    kern_return_t       err;
    mach_port_t         port = MACH_PORT_NULL;
    err = mach_port_allocate(mach_task_self (),
                              MACH_PORT_RIGHT_RECEIVE, &port);
    if(err != KERN_SUCCESS)
    {
        mach_error("Can't allocate mach port\n", err);
        return (-1);
    }

    err = mach_port_insert_right(mach_task_self (),
                                  port,
                                  port,
                                  MACH_MSG_TYPE_MAKE_SEND);
    if(err != KERN_SUCCESS)
    {
        mach_error("Can't insert port right\n", err);
        return (-1);
    }

    (*recv_port) = port;
    return (0);
}

pid_t
fork_pass_port(mach_port_t pass_port, int32_t (*child_start)(mach_port_t port, void *arg), void *arg)
{
    pid_t pid = 0;
    int32_t rtrn = 0;
    kern_return_t err;
    mach_port_t special_port = MACH_PORT_NULL;

    /* Setup the mach port. */
    if(setup_recv_port(&pass_port) != 0)
    {
        printf("Can't setup mach port\n");
        return (-1);
    }

    /* Grab our current task's(process's) HOST_NAME special port. */
    err = task_get_special_port(mach_task_self(), TASK_HOST_PORT, &special_port);
    if(err != KERN_SUCCESS)
    {
        mach_error("Can't get special port:\n", err);
        return (-1);
    }

    /* Set the HOST_NAME special port as the parent recv port.  */
    err = task_set_special_port(mach_task_self(), TASK_HOST_PORT, pass_port);
    if(err != KERN_SUCCESS)
    {
        mach_error("Can't set special port:\n", err);
        return (-1);
    }

    pid = fork();
    if(pid == 0)
    {
        mach_port_t host_port = MACH_PORT_NULL;
        mach_port_t port = MACH_PORT_NULL;

        /* In the child process grab the port passed by the parent. */
        err = task_get_special_port(mach_task_self(), TASK_HOST_PORT, &pass_port);
        if(err != KERN_SUCCESS)
        {
            mach_error("Can't get special port:\n", err);
            return (-1);
        }

        /* Create a port with a send right. */
        if(setup_recv_port(&port) != 0)
        {
            printf("Can't setup mach port\n");
            return (-1);
        }

        /* Send port to parent. */
        rtrn = send_port(pass_port, port);
        if(rtrn < 0)
        {
            printf("Can't send port\n");
            return (-1);
        }

        /* Now that were done passing the mach port, start the function passed by the caller. */
        child_start(pass_port, arg);

        /* Exit and clean up the child process. */
        _exit(0);
    }
    else if(pid > 0)
    {
        mach_port_t child_port = MACH_PORT_NULL;

        rtrn = recv_port(pass_port, &child_port);
        if(rtrn < 0)
        {
            printf("Can't recv port\n");
            return (-1);
        }

        /* Reset parents special port. */
        err = task_set_special_port(mach_task_self(), TASK_HOST_PORT, special_port);
        if(err != KERN_SUCCESS)
        {
            mach_error("Can't set special port:\n", err);
            return (-1);
        }

        return (0);
    }
    else
    {
        /* Error, so cleanup the mach port. */
        err = mach_port_deallocate(mach_task_self(), pass_port);
        if(err != KERN_SUCCESS)
        {
            mach_error("Can't deallocate mach port\n", err);
            return (-1);
        }

        perror("fork");

        return (-1);
    }
}

static int32_t start(mach_port_t port, void *arg)
{
    printf("Started\n");

    return (0);
}

int main(void)
{
    char *arg = "argument";
    mach_port_t port = MACH_PORT_NULL;

    pid_t pid = fork_pass_port(port, start, arg);
    if(pid < 0)
    {
        printf("Can't fork and pass msg port\n");
        return (-1);
    }

    return (0);
}

Source: (StackOverflow)