question
stringlengths
25
894
answer
stringlengths
4
863
I want to provide a user space function that obtains TCP connection stats by implementing a kernel extension. From examining the TCP source, I see the tcpcp struct holds such stats. How can I, given a socket handle from user space, obtain the associated tcpcb struct via a kernel extension and return the stats to user space?
Direct answer to the question: I believe you can't get at this information from a kext without using some private headers to get the memory layout of the structs involved. This will break if/when Apple changes the layout of those structs. However, it looks like you don't really care about the kext aspect and are happy to get the information from userspace, so have you investigated theTCPCTL_PCBLISTsysctl? This gives you the CBs for the TCP connections in the system, and thextcpcb64struct does contain the fields you're after. This mechanism might not be granular enough for your purposes though.
This question already has answers here:Short circuit behavior of logical expressions in C in this example(1 answer)Increment and logical operators precedence [duplicate](3 answers)Closed8 years ago. ``` #include <stdio.h> int main(void) { int i = -3, j = 2, k = 0, m; m = ++i && ++j || ++k; printf("%d %d %d %d\n",i,j,k,m); return 0; } ``` I am trying to learn about associativity and precedence of operators in C. Here, The output comes out to be-2 3 0 1, but I think the output should be-2 3 1 1becausekis also pre-incremented. Why that won't be the answer? Thanks!
the||has short-circuit evaluation, which means that the right hand side gets evaluated only if the left hand side isfalse. In your case this doesn't happen since bothiandjhave values different than0after being incremented, so the++kdoesn't get executed The same behavior occurs when you have a&&in which the LHS expressions evaluates tofalse
On Linux/Mac/Windows, is it possible to access the TCP timestamp and/or RTT in user space of a connected TCP socket? I'm referring to the TCP timestamp and associated RTT calculation enabled byRFC 1323. Obviously, I could utilize a raw socket, but the socket would neither be connected or capable of sending TCP packets on Windows (post XP Update 3, I believe).
I want to append more information. For iOS/MacOSX, I found another method which is very similar withLinux tcp_info. It'sstruct tcp_connection_info. You can find it in theusr/include/netinet/tcp.hof the iOS/MacOSX xcode sdk. You can use it as the following: ``` int length = sizeof(struct tcp_connection_info); getsockopt(socket_fd, IPPROTO_TCP, TCP_CONNECTION_INFO, (void *)info, (socklen_t *)&length); ``` I tested it on iOS 10.2.
I'm trying to understand how this list works, by looking at the macro expansion of list_for_each_entry, the condition to exit the for is ``` &pos->list_member != head ``` but I see code that written like this and works fine, I don't understand why it works ``` struct entry { int some_var; struct list_head list; }; struct global { struct list_head entries_list; }; struct global Global; INIT_LIST_HEAD(&global.entries_list) entry = kmalloc(new_entry..) list_add_tail(&entry,&Global.entries_list); list_for_each_entry(entry,&Global.entries_list,list) { } ``` So by the end of the for, I should expect&entry->list == &Global.entries_list? How is this possible?
So by the end of the for, I should expect&entry->list == &Global.entries_list? Yes. How is this possible? Condition above means thatentryisfake: it is not an element in the list, but just a raw pointer, which satisfies to given condition.
Does the Win32 API provide any means to retrieve thestructMSGvalue that theWindowProcis currently processing, from inside the proc? P.S. I can't use notorious global constructs like static, it will surely bite me later on.If it's relevant, the reason I need this is to pump the messages to other handlers (that I know of only at runtime) for the actual processing, and I don't want to lose any data as long as I can help it.
The first four members of theMSG structureare passed to the window procedure. The remaining members can be retrieved through API calls. You can get theptvalue usingGetMessagePosand thetimevalue usingGetMessageTime.
I would like to know how the memory is allocated to #define variables in C. ``` #define VAR1 10 ``` I have 2 questions... What's the type of VAR1?In which memory segment VAR1 is stored?
In which memory segment VAR1 is stored? In none of the segment. VAR1is relevant only in pre-processing stage and does not have any identity at run time. During pre-processing all instances ofVAR1are replaced with10so there is no memory requirement at run time because10is an integer literal. What's the type of VAR1? VAR1is replaced with10at pre-processing stage.10being aninteger literal, we can say type orVAR1isint. Moral:Macros arenotvariables.
I want to provide a user space function that obtains TCP connection stats by implementing a kernel extension. From examining the TCP source, I see the tcpcp struct holds such stats. How can I, given a socket handle from user space, obtain the associated tcpcb struct via a kernel extension and return the stats to user space?
Direct answer to the question: I believe you can't get at this information from a kext without using some private headers to get the memory layout of the structs involved. This will break if/when Apple changes the layout of those structs. However, it looks like you don't really care about the kext aspect and are happy to get the information from userspace, so have you investigated theTCPCTL_PCBLISTsysctl? This gives you the CBs for the TCP connections in the system, and thextcpcb64struct does contain the fields you're after. This mechanism might not be granular enough for your purposes though.
This question already has answers here:Short circuit behavior of logical expressions in C in this example(1 answer)Increment and logical operators precedence [duplicate](3 answers)Closed8 years ago. ``` #include <stdio.h> int main(void) { int i = -3, j = 2, k = 0, m; m = ++i && ++j || ++k; printf("%d %d %d %d\n",i,j,k,m); return 0; } ``` I am trying to learn about associativity and precedence of operators in C. Here, The output comes out to be-2 3 0 1, but I think the output should be-2 3 1 1becausekis also pre-incremented. Why that won't be the answer? Thanks!
the||has short-circuit evaluation, which means that the right hand side gets evaluated only if the left hand side isfalse. In your case this doesn't happen since bothiandjhave values different than0after being incremented, so the++kdoesn't get executed The same behavior occurs when you have a&&in which the LHS expressions evaluates tofalse
On Linux/Mac/Windows, is it possible to access the TCP timestamp and/or RTT in user space of a connected TCP socket? I'm referring to the TCP timestamp and associated RTT calculation enabled byRFC 1323. Obviously, I could utilize a raw socket, but the socket would neither be connected or capable of sending TCP packets on Windows (post XP Update 3, I believe).
I want to append more information. For iOS/MacOSX, I found another method which is very similar withLinux tcp_info. It'sstruct tcp_connection_info. You can find it in theusr/include/netinet/tcp.hof the iOS/MacOSX xcode sdk. You can use it as the following: ``` int length = sizeof(struct tcp_connection_info); getsockopt(socket_fd, IPPROTO_TCP, TCP_CONNECTION_INFO, (void *)info, (socklen_t *)&length); ``` I tested it on iOS 10.2.
I'm trying to understand how this list works, by looking at the macro expansion of list_for_each_entry, the condition to exit the for is ``` &pos->list_member != head ``` but I see code that written like this and works fine, I don't understand why it works ``` struct entry { int some_var; struct list_head list; }; struct global { struct list_head entries_list; }; struct global Global; INIT_LIST_HEAD(&global.entries_list) entry = kmalloc(new_entry..) list_add_tail(&entry,&Global.entries_list); list_for_each_entry(entry,&Global.entries_list,list) { } ``` So by the end of the for, I should expect&entry->list == &Global.entries_list? How is this possible?
So by the end of the for, I should expect&entry->list == &Global.entries_list? Yes. How is this possible? Condition above means thatentryisfake: it is not an element in the list, but just a raw pointer, which satisfies to given condition.
Does the Win32 API provide any means to retrieve thestructMSGvalue that theWindowProcis currently processing, from inside the proc? P.S. I can't use notorious global constructs like static, it will surely bite me later on.If it's relevant, the reason I need this is to pump the messages to other handlers (that I know of only at runtime) for the actual processing, and I don't want to lose any data as long as I can help it.
The first four members of theMSG structureare passed to the window procedure. The remaining members can be retrieved through API calls. You can get theptvalue usingGetMessagePosand thetimevalue usingGetMessageTime.
I would like to know how the memory is allocated to #define variables in C. ``` #define VAR1 10 ``` I have 2 questions... What's the type of VAR1?In which memory segment VAR1 is stored?
In which memory segment VAR1 is stored? In none of the segment. VAR1is relevant only in pre-processing stage and does not have any identity at run time. During pre-processing all instances ofVAR1are replaced with10so there is no memory requirement at run time because10is an integer literal. What's the type of VAR1? VAR1is replaced with10at pre-processing stage.10being aninteger literal, we can say type orVAR1isint. Moral:Macros arenotvariables.
I'm trying to understand how this list works, by looking at the macro expansion of list_for_each_entry, the condition to exit the for is ``` &pos->list_member != head ``` but I see code that written like this and works fine, I don't understand why it works ``` struct entry { int some_var; struct list_head list; }; struct global { struct list_head entries_list; }; struct global Global; INIT_LIST_HEAD(&global.entries_list) entry = kmalloc(new_entry..) list_add_tail(&entry,&Global.entries_list); list_for_each_entry(entry,&Global.entries_list,list) { } ``` So by the end of the for, I should expect&entry->list == &Global.entries_list? How is this possible?
So by the end of the for, I should expect&entry->list == &Global.entries_list? Yes. How is this possible? Condition above means thatentryisfake: it is not an element in the list, but just a raw pointer, which satisfies to given condition.
Does the Win32 API provide any means to retrieve thestructMSGvalue that theWindowProcis currently processing, from inside the proc? P.S. I can't use notorious global constructs like static, it will surely bite me later on.If it's relevant, the reason I need this is to pump the messages to other handlers (that I know of only at runtime) for the actual processing, and I don't want to lose any data as long as I can help it.
The first four members of theMSG structureare passed to the window procedure. The remaining members can be retrieved through API calls. You can get theptvalue usingGetMessagePosand thetimevalue usingGetMessageTime.
I would like to know how the memory is allocated to #define variables in C. ``` #define VAR1 10 ``` I have 2 questions... What's the type of VAR1?In which memory segment VAR1 is stored?
In which memory segment VAR1 is stored? In none of the segment. VAR1is relevant only in pre-processing stage and does not have any identity at run time. During pre-processing all instances ofVAR1are replaced with10so there is no memory requirement at run time because10is an integer literal. What's the type of VAR1? VAR1is replaced with10at pre-processing stage.10being aninteger literal, we can say type orVAR1isint. Moral:Macros arenotvariables.
I am trying to convert from arduino to avr-c. I get the errorSREGis undeclared. Do you know whatSREGis?.
SREGis theStatusRegister. It is#define'd in one of the AVR headers, so you are probably missing an#include(perhapsavr/io.horavr/common.h).
I am trying to pass an audio stream to C/C++ Addon. But first I want to understand and implement some basic examples. The whole objective is to use stdin and stdout to pipe information between nodeJS and the addon. In nodejs I can see the stdout with this code: ``` var fs = require('fs'); var readableStream = fs.createReadStream('file.txt'); var data = ''; readableStream.on('data', function(chunk) { data+=chunk; }); readableStream.on('end', function() { console.log(data); }); ``` But now, How can I pass it to c/c++ addon?
You cannot pass data directly from NodeJS to C++. You can write/develop your own Node addon/module in C++ which exposes some functions to (Node) JS then pass the data to these functions: ``` var myModule = require('mymodule'); // The Node addon you wrote myModule.processData(data); ``` Now,processDatareceives data from JS and it is a C++ implementation so there you go.
for(;;)statement is an empty statement. Though being an empty condition, compiler should treat it asnullstatement which is equivalent to0, i.e FALSE. Therefore, according to me, it should not get evaluated. But to my surprise, compiler sends the true signal. Kindly explain.
C standard states that if the condition is present, then it should treated as if it had a non-zero value. 6.8.5.3, p2 The for statement for ( clause-1 ; expression-2 ; expression-3 )Both clause-1 and expression-3 can be omitted.An omitted expression-2 is replaced by a nonzero constant. (emphasis mine) This is inconsistent withwhileloop though as the conditional expression can't be left empty in a while loop. But that's how C is on many aspects :)
I'm writing some audio processing software and I need to know how to do saturated arithmetic with SSE2 double-precision instructions. My values need to be normalized between -1 and 1. Is there a clever way to do this with SSE2 intrinsic or do I need a 2 sets of if/else statements (one for each value)?
To clip double precision values to a range of -1.0 to +1.0 you can use max/min operations. E.g. if you have a buffer,buff, of Ndoublevalues: ``` const __m128d kMax = _mm_set1_pd(1.0); const __m128d kMin = _mm_set1_pd(-1.0); for (int i = 0; i < N; i += 2) { __m128d v = _mm_loadu_pd(&buff[i]); v = _mm_max_pd(v, kMin); v = _mm_min_pd(v, kMax); _mm_storeu_pd(&buff[i], v); } ```
I'm totally new to C. I tried the following code, expecting that the child's ppid would match the parent's pid, but this is not the case. ``` int main() { int pid; printf("I'm process with pid=%d\n", getpid()); switch (pid = fork()) { case -1: perror("fork"); exit(1); case 0: printf("I'm the child process: pid=%d, ppid=%d\n", getpid(), getppid()); break; default: printf("I'm the parent process: pid=%d, ppid=%d\n", getpid(), getppid()); break; } exit(0); } ``` ``` > gcc -o fork fork.c > ./fork I'm process with pid=16907 I'm the parent process: pid=16907, ppid=6604 I'm the child process: pid=16908, ppid=1 // <-- expected ppid=16907, why 1? > ``` What did I do wrong ?
It is likely the parent process has already exited and no longer exists. You could try some delay in the parent.
Today I started learning OpenCL when I came across function specifier like_kernel. Than I searched for it and I found many function specifier like_inline_noreturn. I want to know what is a function specifier and what's its usage? I have read many C programming books but never found such term? ``` _Noreturn ``` Is the above specifier similar tovoid?
Here's a good link explaining function specifiers I have quoted an excerpt that more accurately answers your specific question: _Noreturn (since C11) - specifies that the function does not return to where it was called from.
I'm writing some audio processing software and I need to know how to do saturated arithmetic with SSE2 double-precision instructions. My values need to be normalized between -1 and 1. Is there a clever way to do this with SSE2 intrinsic or do I need a 2 sets of if/else statements (one for each value)?
To clip double precision values to a range of -1.0 to +1.0 you can use max/min operations. E.g. if you have a buffer,buff, of Ndoublevalues: ``` const __m128d kMax = _mm_set1_pd(1.0); const __m128d kMin = _mm_set1_pd(-1.0); for (int i = 0; i < N; i += 2) { __m128d v = _mm_loadu_pd(&buff[i]); v = _mm_max_pd(v, kMin); v = _mm_min_pd(v, kMax); _mm_storeu_pd(&buff[i], v); } ```
I'm totally new to C. I tried the following code, expecting that the child's ppid would match the parent's pid, but this is not the case. ``` int main() { int pid; printf("I'm process with pid=%d\n", getpid()); switch (pid = fork()) { case -1: perror("fork"); exit(1); case 0: printf("I'm the child process: pid=%d, ppid=%d\n", getpid(), getppid()); break; default: printf("I'm the parent process: pid=%d, ppid=%d\n", getpid(), getppid()); break; } exit(0); } ``` ``` > gcc -o fork fork.c > ./fork I'm process with pid=16907 I'm the parent process: pid=16907, ppid=6604 I'm the child process: pid=16908, ppid=1 // <-- expected ppid=16907, why 1? > ``` What did I do wrong ?
It is likely the parent process has already exited and no longer exists. You could try some delay in the parent.
Today I started learning OpenCL when I came across function specifier like_kernel. Than I searched for it and I found many function specifier like_inline_noreturn. I want to know what is a function specifier and what's its usage? I have read many C programming books but never found such term? ``` _Noreturn ``` Is the above specifier similar tovoid?
Here's a good link explaining function specifiers I have quoted an excerpt that more accurately answers your specific question: _Noreturn (since C11) - specifies that the function does not return to where it was called from.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed8 years ago.Improve this question I have learned how to handle all data types except, strings. So, can anyone help me with the strings?
You can define a string as an array of chars or a pointer to a char, strings terminate with a null (0 byte) Examples: ``` char c[]="abcd"; char c1[5]="abcd"; char c2[]={'a','b','c','d','\0'}; char c3[5]={'a','b','c','d','\0'}; char *c4="abcd"; ```
I would like to set multiple breakpoints at once in different files in GDB. Is it possible to have a script or any other way which I can run once I enter GDB debugger and have all the breakpoints set instead of setting them one by one using traditionalset breakcommand. All the resources I searched pointed to how to set breakpoints effectively. But, nothing seems to address my concern.
You can use thesource commandin gdb. You can also put the commands in the.gdbinitfile which will be sourced when you start gdb. Put the commands there and they will be run without doing anything more.
Could I somehow use getchar() to run through a command line until I hit a '\n'. Say I want to scan in all the values I enter such as. 21 23 1 78 54 '\n'. I want to scan all the five values into an array. I am unable to scan them in. Is it because of the spacing between each value? Or is there a function we could use to do it ? Thanks in Advance
If you are not bent on usinggetchar()then I have a straightforward solution usingscanfwith the%dconversion specifier: ``` while (i < ARRAY_SIZE && scanf("%d", &a[i]) == 1) i++ ; ``` The%dconversion specifier tellsscanfto skip over any leading whitespace and read up to the next non-digit character. The return value is the number of successful conversions and assignments. Since we're reading a single integer value, the return value should be 1 on success.
I have 2 problems with this function: ``` char * getHeader( char localString[], int seperatorNum) { int maxL=50; const char seperator=':'; char newdata[maxL]; int counter=0; for(int k=0;k<maxL;k++) { if ( localString[k]== seperator ) { counter++; if(counter==seperatorNum) { Serial.println(newdata); return newdata; } } newdata[k]=localString[k]; } } ``` When I print thenewdataI get garbage, butlocalString[k]is showing good results.How would I return the array-is my way good? Edit: i am getting bb after each and every result . so : ``` aaa:sss (send) aaabb (get) kkk:ooo (send) kkkbb (get) ppp:ttt pppbb ```
``` newdata[k]=localstring[k]; ``` If should come just after ``` for(int k=0;k<maxL;k++) { //here ``` And if that is not solving it then please provide related complete code.
I have the packages installed and in the parent directorty of gcc-4.9.2 and when I specify where the libs are such as --with-gmp it says: ``` configure: WARNING: you should use --build, --host, --target checking build system type... Invalid configuration `gmp': machine `gmp' not recognized configure: error: /bin/sh gcc-4.9.2/config.sub gmp failed ``` Command: ``` gcc-4.9.2/configure --with-gmp gmp --enable-languages=c,c++ ```
The correct way to use--with-gmpis--with-gmp=the/path/to/gmpnote the=between and there should be no space. What is happening is configure is treating--with-gmp gmpas two unrelated arguments and is treatinggmpas the build, which is usually specified via--build=your-build-targetbut it seems if you just specify an argument without a-or--it treats it as the build option.
I read that the parent and the child will work on the identical code after thefork()system call. I cannot understand the point of doing afork()as I cannot understand what good will it do in executing the same code twice.
The return value offork()is different in the child and parent processes, so you'll typically have something along the lines of ``` pid_t child_pid = fork() if (child_pid == 0) { // do stuff in child process } else { // do stuff in parent process } ```
my code is not working as i expected.if s the number words to be printed.then s-1 will be the number of spaces between them.in the while loop scanf reads the characters one bye one if it encounters a space it increments k.when k equals s-1 the break statement is executed. ``` #include<stdio.h> #include<string.h> int main(void) { int i,j,k=0,s; char a[100]; scanf("%d",&s); i=0; while(1) { scanf("%c",&a[i]); i++; if(a[i]==' ') k++; if(k==(s-1)) break; } puts(a); } ```
``` scanf("%c",&a[i]); i++; if(a[i]==' ') k++; ``` When you comparea[i]against' ', it's not assigned yet. This leads you to undefined behavior.
This question already has answers here:Array index out of bound behavior(10 answers)Closed8 years ago. So I'm learning C, I have experience with Java and Python, and this is a really curious thing which is happening. When I run this code, the output is Hello7 ``` #include <stdio.h> int main() { int a[1]; a[1]=1; a[2]=2; a[3]=7; printf("Hello%d",a[3]); } ``` But how is GCC able to print out Hello7 if the maximum size of the array is 1?
A C array is no more than a sequence of contiguous memory locations. When you ask C to give you a certain index from the array, it takes the start of the array and adds on the necessary number of bytes to get the the appropriate memory location. It doesn't know how big the array is supposed to be; in C that job is left to you as the programmer.
How can I know what linux package has a certain .h file ? Specifically I need the package for ``` #include "secmodi.h" #include "secmodti.h" ``` I imagine these are files related to libnss3 package. They're not in libnss3-dev package, which has only secmod.h and secmodt.h files. Where can I find these ? But it would be nice to know how I could find it if I need it again for other files. I tryied only google and duckgogo as I don't know any specific search engine. Edit I tried to use dpkg -S, apt-file find and packages.ubuntu.com and couldn't find it. I wonder... could this be an older version of this package or something ?
I found it in the package source. I downloaded it withsources libnss3-dev
I dont understand why they are not accepting this as the solution,They are saying its a wrong answer:- ``` #include <stdio.h> int main(void) { int val=0; printf("Input:- \n"); do { scanf("%d",&val); printf("%d \n",val); } while(val < 42); return 0; } ```
Two mistakes: Remove this line-printf("Input:- \n");In question you have to print before coming 42. If 42 has come you have to break. Like this: ``` if(n!=42) printf("%d\n",n); else break; ```
In a kernel module, how do you compare an ipv6 address if you are given astruct sockaddr_storageand an ipv6 string literal "::1"? On linux 3.16.0-4-686-pae (x86). ``` struct sockaddr_storage ss; ... if(ss.ss_family == AF_INET6) { // ipv6 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss; // compare ipv6 address struct in6_addr addr; inet_pton(AF_INET6, "::1", &addr); // error: implicit declaration of function ‘inet_pton’ if( (memcmp(addr.s6_addr, sin6->sin6_addr.s6_addr, sizeof(struct in6_addr)) == 0) && (htons(25) == sin6->sin6_port) ) return -EPERM; } ```
The parsing function you used is userspace, that won't work in the kernel. The actual comparison is probably better done withipv6_addr_cmp()rather than a barememcmp().
``` int isEmptyArray (struct arrayBagStack * b) { return(!b->count); } ``` I have this code snippet that is shown as a correct answer. I do not understand the concept that is shown of returning a (!) Not Int value when the Int value is expected. Can someone explain why this would work and what is the expected behavior? countis a int member variable ofstruct arrayBagStack.
There is no change of type happening here. The not operator (!) simply computes another integer value, which is then returned. In this case, it's being used to convert the count into a true/false value to answer the question whether the array is empty. Ifb->countis 0,!0is1, which means "true". If it's any other value,!will convert that to0, i.e. "false". In my opinion code like this fails to be optimally clear; it should just be: ``` return b->count != 0; ``` Which generates the exact same values for all values ofcount, but is way clearer.
This question already has answers here:UDP receiving data on multiple ports(2 answers)Closed8 years ago. i opened a UDP socket on IP 192.168.210.120 and port 5000. and i want to recieve data on two different port (5000,6000). please guide
That's not possible with a single socket. By definition, UDP sockets can only bind to a single port. That's how these sockets work. You can, however, open two sockets. And then, maybe using two accepting threads, maybe using other mechanisms (POSIXselect) detect connections to these. How you can juggle multiple listening UDP sockets depends on your programming language/socket abstraction.
``` for (int i = 0; i < n; i++) for(int j = 0; j < i; j++) printf("Hello World"); ``` I think the answer should be n(n)! because the outer loop executes n times and the inner loop (n)! times.
Well you can introduce a counter to be sure ``` int counter = 0; for (int i = 0; i < n; i++) for(int j = 0; j < i; j++) { printf("Hello World"); counter ++; } ``` Or take a pen : ``` i = 1 j = 0 Hello World i = 2 j = 0 Hello World j = 1 Hello World i = 3 j = 0 Hello World j = 1 Hello World j = 2 Hello World i = 4 j = 0 Hello World j = 1 Hello World j = 2 Hello World j = 3 Hello World [...] ``` And you can see a pattern... 1 + 2 + 3 + ... ?
``` int isEmptyArray (struct arrayBagStack * b) { return(!b->count); } ``` I have this code snippet that is shown as a correct answer. I do not understand the concept that is shown of returning a (!) Not Int value when the Int value is expected. Can someone explain why this would work and what is the expected behavior? countis a int member variable ofstruct arrayBagStack.
There is no change of type happening here. The not operator (!) simply computes another integer value, which is then returned. In this case, it's being used to convert the count into a true/false value to answer the question whether the array is empty. Ifb->countis 0,!0is1, which means "true". If it's any other value,!will convert that to0, i.e. "false". In my opinion code like this fails to be optimally clear; it should just be: ``` return b->count != 0; ``` Which generates the exact same values for all values ofcount, but is way clearer.
This question already has answers here:UDP receiving data on multiple ports(2 answers)Closed8 years ago. i opened a UDP socket on IP 192.168.210.120 and port 5000. and i want to recieve data on two different port (5000,6000). please guide
That's not possible with a single socket. By definition, UDP sockets can only bind to a single port. That's how these sockets work. You can, however, open two sockets. And then, maybe using two accepting threads, maybe using other mechanisms (POSIXselect) detect connections to these. How you can juggle multiple listening UDP sockets depends on your programming language/socket abstraction.
``` for (int i = 0; i < n; i++) for(int j = 0; j < i; j++) printf("Hello World"); ``` I think the answer should be n(n)! because the outer loop executes n times and the inner loop (n)! times.
Well you can introduce a counter to be sure ``` int counter = 0; for (int i = 0; i < n; i++) for(int j = 0; j < i; j++) { printf("Hello World"); counter ++; } ``` Or take a pen : ``` i = 1 j = 0 Hello World i = 2 j = 0 Hello World j = 1 Hello World i = 3 j = 0 Hello World j = 1 Hello World j = 2 Hello World i = 4 j = 0 Hello World j = 1 Hello World j = 2 Hello World j = 3 Hello World [...] ``` And you can see a pattern... 1 + 2 + 3 + ... ?
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed8 years ago.Improve this question I have a couple of questions.I need to write a program(winapi) that will create a buffer of a fixed size, then append strings to it and returns it.1. Is it even possible for "main" to return a buffer? 2. How should I create, append string and return it?I am not new to C, but I have very little experience with buffers and strings handling.Thank you!
Is it even possible for "main" to return a buffer? No and you shouldn't.What should main() return in C and C++? How should I create, append string and return it? ``` char aString[FIXED_SIZE]; memset(aString, 0, sizeof aString); strcpy(aString, "This is a string"); ```
I am trying to move from arduinos to AVR C. Would somebody know how to remove the arduino bootloader from the microcontroller? Is there a different process for the different atmega microcontrollers like the 32u4, 328, or 2560? Thanks.
The Arduino bootloader will be removed when you program the atmega using a programmer. When you program Arduino using the Arduino bootloader it knows how to write to the image such that the bootloader is preserved. When you create an image from AVR C and flash it to the atmega the image will overwrite the bootloader, when your atmega is next reset it will now run your image instead of the bootloader. The process will be the same regardless of the part however your project will need to be set up appropriately.
I am usingfp = pcap_open_dead(DLT_EN10MB,65535);to capture frames in pcap format. But whatfp = pcap_open_dead(**DLT_XXX** )should I useif I want to skip the ethernet header. My module is working on layer 3 , so I want to capture packets starting from layer 3. ``` fp = pcap_open_dead(DLT_EN10MB,65535); if (NULL == fp) { FPA_ERROR_PRINT("unable to open the dead interface \n"); return 1; ``` Any help will on this will be highly appreciated. Thanks in advance.
I don't think you can. You need to manually skip the Ethernet header part when parsing the packet buffer.
I am trying to compile pthreads for MSVC2015 and found some strange code. ``` localPtr->wNodePtr->spin := PTW32_TRUE; ``` What is this line doing?
As others pointed out:=is not a valid C-operator. However, this "operator":=is found twice inthe current "PThread for Windows" source release which seems to be as of v2.9.1. Both occurencies appear inptw32_OLL_lock.c, which proclaims to "implements extended reader/writer queue-based locks", but does not seem to be part of thepthread*.dllbuild, so the fileptw32_OLL_lock.cis not passed to the compiler. Interesting enough the source file in question contains anint main()and is not in thetestsub-directory. All in all this seems to be alpha, beta or it's simply noise, so just delete it.
If I open a file using the following code: ``` FILE *file = fopen("D:\\1.mp4", "rb"); ``` This will not lock the file, so for example I can open this file using Notepad and write to it! So is there a way I can make sure that no other application is allowed to write to this file, or should I use WinAPI to accomplish this?
The windows feature you want to use is the "sharing mode." You can set it using the_fsopenfunction. To deny write access use_SH_DENYWRas the third parameter.
I have the following small program which reproduces a trig error in my larger project: ``` #define _USE_MATH_DEFINES #include <math.h> #include <stdio.h> #define R2D(trig_fn, val) trig_fn (val * (180.0 / M_PI)) int main() { printf("%f\n", R2D(atan, 2.5)); return 0; } ``` The expected result of atan(2.5) converted from radians to degrees is 68.1985..., but instead, this program outputs 1.563815, which is nowhere near the correct answer. I preprocessed this out to a file; the problem isn't in the macro which was my first guess too; the macro expands properly (atan (2.5 * (180.0 / 3.14159265358979323846))).
double atan(double x);Returns the principal value of the arc tangent of x, expressed inradians. The output is in radians, not degrees. You need to convert the result of the function to degrees. The input remains a simple unitless number. ``` #define R2D(trig_fn, val) (trig_fn(val) * (180.0 / M_PI)) ```
As per my knowledge range of unsigned char in C is 0-255. but when I executed the below code its printing the 256 as output. How this is possible? I have got this code from "test your C skill" book which say char size is one byte. ``` main() { unsigned char i = 0x80; printf("\n %d",i << 1); } ```
Because the operands to<<*undergointeger promotion. It's effectively equivalent to(int)i << 1. * This is true for most operators in C.
``` #include <stdio.h> int main() { int x=5; printf("%d", printf("%d %d",x,x)); } ``` How is the output5 53can someone explain ? I tried myself and I think the answer should be5 5 2
The return value ofprintfis the number of characters transmitted to the output streamor negative value if an output error or an encoding error (for string and character conversion specifiers) occurred (fromhere, emphasis mine) and "5 5" arethreecharacters (namely "five space five"). So the last number printed is 3.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed8 years ago.Improve this question If i'm usingminstead of~mthen the code gives me the expected hexadecimal value of 32 but here it's givingffffffdfas output. EDITI know how bitwise~NOT operator works. But i'm not understanding this.Could somebody explain this...?? ``` #include<stdio.h> int main() { unsigned int m = 32; printf("%x\n", ~m); //ffffffdf is printed as output return 0; } ```
Every hexadecimal digit is four bits. Since you got 8 hexadecimal digits your integers seems to be 8*4=32 bit. The NOT of 32 =000000000000000000000000000010000would be something like11111111111111111111111111101111which would be the hexadecimal digits above.
I have the code below.The problem is that I am taking a two dimensional array with a rows and 2 col.The 1st col is for storing values and 2nd as a flag.The problem arises when I initialize my flag the values are also getting affected. ``` #include<stdio.h> int main() { int a,b; scanf("%d%d",&a,&b); int arr[a][1]; int i,j,k,sum=0; for(i=0;i<a;i++) { scanf("%d",&arr[i][0]); } for(i=0;i<a;i++) { printf("%d\n",arr[i][0]); } for(j=0;j<a;j++) { arr[j][1]=0; } for(i=0;i<a;i++) { printf("%d\n",arr[i][0]);//Different Values } } ```
int arr[a][1];There is only one column and not two.You should use ``` int arr[a][2]; ```
This question already has answers here:Difference between null == x and x == null? [duplicate](5 answers)Closed8 years ago. I'm looking through some code and I found some strange conditionals, namely: ``` if (NULL != buf) {...} ``` I was wondering if there was a particular reason for writing the conditional like this, instead of ``` if(buf != NULL){...} ``` I can't see any reason to do it the first way off the top of my head, but I don't think it was a mistake. To me, it seems like they accomplish the same thing, but the second way is way more intuitive. Is there some specific reason to use the first conditional?
Yes, it's called "Yoda conditions". The idea is to not accidentally assign a value when you mean to be doing a check. Most modern compilers should catch it.
I have an input fed from vhdl code into Nios system programmed in C language. In the vhdl, ``` signal input : ufixed(9 downto -6); ``` when I fed this input to C compiler, in the terminal window, it is shown, ``` input = 256 ``` In vhdl, input is declared to have 10 decimal points and 6 fractional points. So, input in binary should look like this:0000000100 000000(which is equivalent to256in decimal) What should I do so that I will get the "input" interpreted as value4in C code? I want both integer and fractional parts, for example, if the input is0000000100 100000, I want to get the value of4.5in C code
In C code you can just divide by a scaling factor to get the equivalent value: ``` float f = (float)input / (1 << 6); // divide by 2^6 = 64 ``` If you only want the integer part then you can just shift out the fractional part: ``` int n = input >> 6; ```
I'm trying to set a simple division in a project, on STM32F10x here what I've done : say I got a float variable: ``` float f =0.0; ............. ``` when I usefthis way : ``` f = 20/5 ; ``` the program can't use the value offwhich is the result of the division, I'm using this value in multiple other functions in the Program, but none of them works meaning that I'dont get an error but the program doesn't work . but when set the value : ``` f = 4 ; ``` everything works fine !any idea why ? I've used : f = (float) 20/5 ;
The compiler treats all floating point numbers without a suffix asdouble. This will blow up on STM32/ARM. Use a suffix, iow20.0f. The reason your cast works is because the result can be determined at compile time. If not, it will blow up again.
I have the following small program which reproduces a trig error in my larger project: ``` #define _USE_MATH_DEFINES #include <math.h> #include <stdio.h> #define R2D(trig_fn, val) trig_fn (val * (180.0 / M_PI)) int main() { printf("%f\n", R2D(atan, 2.5)); return 0; } ``` The expected result of atan(2.5) converted from radians to degrees is 68.1985..., but instead, this program outputs 1.563815, which is nowhere near the correct answer. I preprocessed this out to a file; the problem isn't in the macro which was my first guess too; the macro expands properly (atan (2.5 * (180.0 / 3.14159265358979323846))).
double atan(double x);Returns the principal value of the arc tangent of x, expressed inradians. The output is in radians, not degrees. You need to convert the result of the function to degrees. The input remains a simple unitless number. ``` #define R2D(trig_fn, val) (trig_fn(val) * (180.0 / M_PI)) ```
As per my knowledge range of unsigned char in C is 0-255. but when I executed the below code its printing the 256 as output. How this is possible? I have got this code from "test your C skill" book which say char size is one byte. ``` main() { unsigned char i = 0x80; printf("\n %d",i << 1); } ```
Because the operands to<<*undergointeger promotion. It's effectively equivalent to(int)i << 1. * This is true for most operators in C.
``` #include <stdio.h> int main() { int x=5; printf("%d", printf("%d %d",x,x)); } ``` How is the output5 53can someone explain ? I tried myself and I think the answer should be5 5 2
The return value ofprintfis the number of characters transmitted to the output streamor negative value if an output error or an encoding error (for string and character conversion specifiers) occurred (fromhere, emphasis mine) and "5 5" arethreecharacters (namely "five space five"). So the last number printed is 3.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed8 years ago.Improve this question If i'm usingminstead of~mthen the code gives me the expected hexadecimal value of 32 but here it's givingffffffdfas output. EDITI know how bitwise~NOT operator works. But i'm not understanding this.Could somebody explain this...?? ``` #include<stdio.h> int main() { unsigned int m = 32; printf("%x\n", ~m); //ffffffdf is printed as output return 0; } ```
Every hexadecimal digit is four bits. Since you got 8 hexadecimal digits your integers seems to be 8*4=32 bit. The NOT of 32 =000000000000000000000000000010000would be something like11111111111111111111111111101111which would be the hexadecimal digits above.
I have the code below.The problem is that I am taking a two dimensional array with a rows and 2 col.The 1st col is for storing values and 2nd as a flag.The problem arises when I initialize my flag the values are also getting affected. ``` #include<stdio.h> int main() { int a,b; scanf("%d%d",&a,&b); int arr[a][1]; int i,j,k,sum=0; for(i=0;i<a;i++) { scanf("%d",&arr[i][0]); } for(i=0;i<a;i++) { printf("%d\n",arr[i][0]); } for(j=0;j<a;j++) { arr[j][1]=0; } for(i=0;i<a;i++) { printf("%d\n",arr[i][0]);//Different Values } } ```
int arr[a][1];There is only one column and not two.You should use ``` int arr[a][2]; ```
This question already has answers here:Difference between null == x and x == null? [duplicate](5 answers)Closed8 years ago. I'm looking through some code and I found some strange conditionals, namely: ``` if (NULL != buf) {...} ``` I was wondering if there was a particular reason for writing the conditional like this, instead of ``` if(buf != NULL){...} ``` I can't see any reason to do it the first way off the top of my head, but I don't think it was a mistake. To me, it seems like they accomplish the same thing, but the second way is way more intuitive. Is there some specific reason to use the first conditional?
Yes, it's called "Yoda conditions". The idea is to not accidentally assign a value when you mean to be doing a check. Most modern compilers should catch it.
I want to compile my C file withclangand then decompile it with withndisasm(for educational purposes). However,ndisasmsays in it's manual that it only works withbinaryand notexecutablefiles: ``` ndisasm only disassembles binary files: it has no understanding of the header information present in object or executable files. If you want to disassemble an object file, you should probably be using objdump(1). ``` What's the difference, exactly? And what doesclangoutput when I run it with a simple C file, an executable or a binary?
An object file contains machine language code,andall sorts of other information. It sounds likendisasmwants just the machine code, not the other stuff. So the message is telling you to use theobjdumputility to extract just the machine code segment(s) from the object file. Then you can presumably runndisasmon that.
I have a structure defined as ``` struct new{ int x; int y; unsigned char *array; }; ``` where I want array to be an array which is initialized dynamically based on user input. Inside main function: ``` struct new *sbi; sbi->array = (unsigned char*)malloc(16 * sizeof(unsigned char)); for(i=0; i<16; i++) { sbi->array[i] = 0; } for(i=0; i<16; i++) printf("Data in array = %u\n", (unsigned int)sbi->array[i]); ``` I am sure I am doing something wrong with the malloc but I am not getting it - it just keeps giving segmentation fault.
You're declaring sbi as a pointer to struct new, but never allocating memory to it. Try this: ``` struct new *sbi; sbi = malloc(sizeof(struct new)); ``` Also, don't cast the results of malloc, as that can mask other errors, and don't forget to check the return value of malloc.
``` #import <stdio.h> int main(void) { int sum,i; sum = 0; for(i=0;i<10;i++) { if(i%2) continue; sum+=i; } printf("\n%d",sum); return 0; } ``` How doesif(i%2)works in the above code?
In computing, the modulo operation finds the remainder after division of one number by another (sometimes called modulus).% is the modulus operator. So i%2 returns the remainder left after i is divided by 2.Therefore if i is odd i%2=1(TRUE)else it is 0(FALSE).(even condition) Therefore if i is even i is added to sum else the loop continues.
How do I iterate over my files variable in an efficient way ? Should I add NULL as my last value, or do something else ? ``` char *files[] = { "c1.txt", "r1.txt", "t2.c", "d.cpp", }; ```
There are several possibilities. You can addNULLas the final entry, as you suggest yourselfIf the array comes from another source (like a file on disk), just keep a counter of the number of lines you're readingBut if the array is given in the source, its length is constant and you can just check how many elements it has (by subtracting the line numbers)Also, the size of a constant array issizeof(files) / sizeof(char*).
I was wondering what's happening in this code from K&R C: ``` #include <stdio.h> int main() { double nc; for (nc = 0; getchar(); ++nc) { ; } printf("%.0f\n", nc); } ``` When I run the code (OS X El Capitan), theforloop doesn't finish and I can't get to theprintfstatement.
Thegetchar()returns the obtained character on success orEOFon failure. Referencehere. Try this ``` for (nc = 0; getchar() != EOF; ++nc) { } ``` Note that,Enterdoesn't meansEOF, it means newline or'\n'. Look at the headerstdio.h, says, ``` #define EOF (-1) ``` Hereyou can see how to simulate an EOF. ``` Windows: Ctrl+Z Unix : Ctrl+D ``` So long story short, you can put any condition in theforloop, like ``` for (nc = 0; getchar() != '\n'; ++nc) { } // break the loop if enter pressed for (nc = 0; getchar() != 'c'; ++nc) { } // break the loop if c pressed . . . ```
I'm trying to write some C that implements some Python (on linux), but I'm seeing the following error when runningPy_Initialize(): ``` ImportError: No module named site ``` I have set PYTHONHOME before the initialization, to the lib directory that contains the site package, as demonstrated: ``` Py_SetPythonHome("/foo/lib/python3"); $ ls /foo/lib/python3/site/ __init__.py __pycache__ ``` I've seen similar issues in my googling but this tends to be resolved by setting PYTHONHOME appropriately, which above shows hasn't worked for me. Does anyone have any idea what I might be missing?
Add the python binary (.exe or whatever) path toPATH.Add your programs (including python code and libraries) directory toPYTHONPATH.
I've found this C program from the web: ``` #include <stdio.h> int main(){ printf("C%d\n",(int)(90-(-4.5//**/ -4.5))); return 0; } ``` The interesting thing with this program is that when it is compiled and run in C89 mode, it printsC89and when it is compiled and run in C99 mode, it printsC99. But I am not able to figure out how this program works. Can you explain how the second argument ofprintfworks in the above program?
C99 allows//-style comments, C89 does not. So, to translate: C99: ``` printf("C%d\n",(int)(90-(-4.5 /*Some comment stuff*/ -4.5))); // Outputs: 99 ``` C89: ``` printf("C%d\n",(int)(90-(-4.5/ -4.5))); /* so we get 90-1 or 89 */ ```
Assuming we have something like this: ``` char * arr[] = { "string1", "string2" }; ``` How do I / more formally (or more accurately) / call this variable: Array of stringsArray of pointers to stringArray of char pointers UPDATE: I will provide asourcein which I read "array of strings" in a response to people saying that this is invalid.
Both Array of pointers to stringArray of char pointers are correct. ``` char * arr[] = { "string1", "string2" }; ``` is an array ofchar*pointers each pointing to the corresponding string literal.
Will I execute shell script .sh if I run code like this: ``` int system (char *s); int sh_exec_ok; //Shell script execution flag sh_exec_ok = system("something/script_name.sh"); ``` What do you suggest me to use to execute shell scripts in C code?
Usingsystemis the right way to run a shell command. Some notes: You should not declaresystemyourself. Instead, do#include <stdlib.h>If portability is a concern, dosystem(NULL). If the return value is non-zero, then a command processor to handle thesystemfunction call is available.It is good practice to use the full path to the shell script, or set the path so it executes the version of the shell script you want to execute.
If file is opened using fopen() and in different mode then is it necessary to close it number of time or it can be closed once at end of code ?
Each time you open the file, you are going to receive different file descriptors or file handles. So you have to close each file handle usingfclose()if opened viafopen()orclose()if opened viaopen().
To read the MBR partition table we use an offset of0x1be, similarly what is the offset for reading the GP(artition)T(able) entries (ie, number of partitions and their sizes). I am writing a C program using "gdisk" to create the partitions, I need to write the filesystems onto these partitions. So for this I need to read the GPT header to get the number of partitions and their allocated sizes.
what is the offset for reading the GPT partition table entries It typically is located inLBA2. To verify check offset 0x30 (base-10 offset 48) to theGPT.
The function I'm making is supposed to return to the maximum value in a vector, and I'm stumped as to why it's not working, here is the code: ``` float max(float vec[], int len) { int i; float max; for (i = 0; i < len; i++) { if (vec[i] > max) { max = vec[i]; } } return max; } ```
maxis uninitialized and using uninitialized variables leads to undefined behavior. ``` float max = vec[0];// Initialize max before using it ```
I need to save lines from a text file into a string and then insert them into a data structure, but with my solution (which I assume is really bad) - I only save words into myline. ``` FILE * ifile = fopen("input.txt", "r"); char line[256]; while(fscanf(ifile, "%s\n", line) == 1) { //inserting "line" into data structure here - no problem with that one } ```
It's almost always a bad idea to use thefscanf()function as it can leave your file pointer in an unknown location on failure. You should usefgets()to get each line. ``` #define SIZE_LINE 256 FILE *ifile = fopen ("input.txt", "r"); if (ifile != NULL) { while (fgets (buff, SIZE_LINE, ifile)) { /* //inserting "line" into data structure here */ } fclose (ifile); } ```
In the code below, method A differs from method B. Can someone explain why _mm_cvt_ss2si rounds to even number when decimal part is exactly 0.5 ? ``` float f; // rounding method A _mm_cvt_ss2si(_mm_load_ss(&f)); // rounding method B (long)((f>0.0f) ? (f + 0.5f):(f -0.5f)); ```
See the comments for the answer to your question. If you want a specific rounding mode in one case, without changing the MXCSR, you can use SSE4.1ROUNDPD / ROUNDPS. (This doesn't do an integer conversion, just rounds the FP value to an integer.) ``` __m128d _mm_round_pd (__m128d a, int rounding) ``` See the manuals for what flags you can pass as aroundingarg.
I saw someone doing this to have array index starting at 1 instead of 0 in C. ``` a = (int *) malloc(sizeof(int)*3) - 1 ``` Is there any risk in this?
Theoretical risk : only null pointers and pointers to, into, or right after an object are valid. Other pointers trigger undefined behaviour on use (if they're dangling) or when creating them through pointer arithmetic. Practical risk : getting pelted by a random code reviewer.
For the following code I am getting output as- Geeks. ``` #include <stdio.h> #define ISEQUAL(X, Y) X == Y int main() { #if ISEQUAL(X, 0) printf("Geeks"); #else printf("Quiz"); #endif return 0; } ``` Explain the reason for such output.
The conditional macro#if ISEQUAL(X, 0)is expanded to#if X == 0. After the pre-processing is over, all the undefined macros are initialized with default value0. Since macroXhas not been defined, it is initialized with0. So, "Geeks" is printed.
This question already has answers here:C Main Loop without 100% cpu(11 answers)Closed8 years ago. I started to play with user interfaces in C with SDL2, window creation and keyboard events. I realised that my app was consuming a lot of CPU (> 95%), probably because I have a while loop waiting for an event to come. How does every other apps manage to not used all the CPU and still be able to respond to an event ?
@artonge, I had the same problem. I wrote a Sleep(..) in the loop and the resource utilization did come down. ``` Sleep(int milliSeconds); ```
I get problem with thislines[k] = lines[k+1]; Here is what I try to do: ``` char lines[MAXLINES][BUFSIZ]; for(k = 0;k < i;k++){ char * tmp = lines[k]; lines[k] = lines[k+1]; lines[k+1] = tmp; change = 1; } ``` Can anyone help me with this? I just want to swap lines[k] with lines[k+1] in the array...
You can't assign to arrays, you needstrcpy() ``` char lines[MAXLINES][BUFSIZ] for (int k = 0 ; k < i ; ++k) { char tmp[BUFSIZ]; strcpy(tmp, lines[k]); strcpy(lines[k], lines[k + 1]); strcpy(lines[k + 1], tmp); change = 1; } ``` sincelines[k]is an array, you can't assign to it but you can copy the contents oflines[k]to a temporary buffer, then copy the contents oflines[1 + k]tolines[k]and finally copy the contents oftmptolines[1 + k].
This question already has answers here:setvbuf not able to make stdin unbuffered(2 answers)Closed8 years ago. I've written a simple C program that is meant to pipestdintostdoutwithout buffering characters: ``` #include <stdio.h> int main (int argc, char *argv[]) { int c; while ((c = getchar()) != -1) { putchar(c); fflush(stdout); } return 0; } ``` However, this program still seems to be buffering characters until newlines, despite the call tofflush. Why is this happening and how can I fix it (if possible)?
In this case, the buffering is done by the terminal driver which doesn't send the input to your program until you pressENTER. So your program doesn't even get any characters andfflush()isn't even called. It's just waiting for input at thegetchar()call.
In the code below, method A differs from method B. Can someone explain why _mm_cvt_ss2si rounds to even number when decimal part is exactly 0.5 ? ``` float f; // rounding method A _mm_cvt_ss2si(_mm_load_ss(&f)); // rounding method B (long)((f>0.0f) ? (f + 0.5f):(f -0.5f)); ```
See the comments for the answer to your question. If you want a specific rounding mode in one case, without changing the MXCSR, you can use SSE4.1ROUNDPD / ROUNDPS. (This doesn't do an integer conversion, just rounds the FP value to an integer.) ``` __m128d _mm_round_pd (__m128d a, int rounding) ``` See the manuals for what flags you can pass as aroundingarg.
I saw someone doing this to have array index starting at 1 instead of 0 in C. ``` a = (int *) malloc(sizeof(int)*3) - 1 ``` Is there any risk in this?
Theoretical risk : only null pointers and pointers to, into, or right after an object are valid. Other pointers trigger undefined behaviour on use (if they're dangling) or when creating them through pointer arithmetic. Practical risk : getting pelted by a random code reviewer.
For the following code I am getting output as- Geeks. ``` #include <stdio.h> #define ISEQUAL(X, Y) X == Y int main() { #if ISEQUAL(X, 0) printf("Geeks"); #else printf("Quiz"); #endif return 0; } ``` Explain the reason for such output.
The conditional macro#if ISEQUAL(X, 0)is expanded to#if X == 0. After the pre-processing is over, all the undefined macros are initialized with default value0. Since macroXhas not been defined, it is initialized with0. So, "Geeks" is printed.
This question already has answers here:C Main Loop without 100% cpu(11 answers)Closed8 years ago. I started to play with user interfaces in C with SDL2, window creation and keyboard events. I realised that my app was consuming a lot of CPU (> 95%), probably because I have a while loop waiting for an event to come. How does every other apps manage to not used all the CPU and still be able to respond to an event ?
@artonge, I had the same problem. I wrote a Sleep(..) in the loop and the resource utilization did come down. ``` Sleep(int milliSeconds); ```
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed8 years ago.Improve this question I am trying using mmap() in c to map the memory. After running the following code, it print 1, because of the sizeof(void*) is 1, so how can we know we did get 1234 bytes memory ``` void *heap_region = NULL; heap_region = mmap(NULL, 1234, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); printf("%lx",sizeof(*heap_region)); ```
If the call succeeded, this means you got (at least) the 1234 bytes you asked for.You know the call succeeded if the returned pointer is notMAP_FAILED. So you could say ``` if(heap_region == MAP_FAILED) { fprintf(stderr, "mmap failed: %s\n", strerror(errno)); exit(1); } else { printf("mmap succeeded: %p\n", heap_region) ... } ```
Does GNU libunistring has an API to determine if a value is UTF16 surrogate? I am new to this library and could not locate one. Can someone help?
Perhapsuc_general_category()is what you are looking for. If you pass it a UTF-16 codeunit, the compiler will extend the 16bit value to 32bits and the function will interpret it as-is as a codepoint. Codepoints U+D800 - U+DFFF are reserved for surrogates only, so the function should returnUC_SURROGATEfor any UTF-16 surrogate codeunit. A non-surrogate codeunit has the same numeric value as its corresponding codepoint in the BMP (surrogates are only needed for codepoints outside the BMP), so the function would return something else.
This question already has answers here:printf with "%d" of numbers starting with 0 (ex "0102") giving unexpected answer (ex '"66")(4 answers)Closed8 years ago. I have a simple program. ``` #include <cstdio> int main() { int num = 000012345; printf("%d\n",num); return 0; } ``` The above program gives 5349. Why ? I mean it should be wrong, but why 5349 ?
Numbers starting with0are octal in c/c++. ``` Octal = 000012345 Decimal= 0×8⁸+0×8⁷+0×8⁶+0×8⁵+1×8⁴+2×8³+3×8²+4×8¹+5×8⁰ = 5349 Binary = 1010011100101 Hex = 14E5 ```
Suppose I have a variable date which is defined with extern in source code, i.e, extern date; then I want to assign a value to it at link time getting time from the computer on which it is compiled and assign to date variable. Is there a way to do that for example in gcc?
Are__TIME__and__DATE__what you are looking for ? If compiling and linking is one step in your scenario you can have your compiler and linker replace those macros with the date and time. If you compile one day and link the other this will not work because the compiler (better: preprocessor) decides which value is inserted. Have a look atthisor other posts here on stackoverflow.
``` #include<stdio.h> int main() { char arr[] = "abcdef"; char *ptr = arr; while(*ptr != '\0') ++*ptr++; printf("%s %s",arr,ptr); return 0; } ``` Output: bcdefg It is printing next alphabet of every alphabet given. What exactly is happening?
There are three operators here suffix++, prefix++, and indirection*. Suffix++has higher precedence that the other two and will be evaluated first. But when using suffix++, the value computation is sequenced before the side effect of updating the stored value, that is incrementing the pointer. So the pointerptrwill get incremented, but the value used in other two operands++and*, will be the old one. Prefix++and indirection operators have the same precedence, but are evaluated from right to left. So indirection*goes first and then prefix++increments the value of the object pointerptrpoints to.
Does GNU libunistring has an API to determine if a value is UTF16 surrogate? I am new to this library and could not locate one. Can someone help?
Perhapsuc_general_category()is what you are looking for. If you pass it a UTF-16 codeunit, the compiler will extend the 16bit value to 32bits and the function will interpret it as-is as a codepoint. Codepoints U+D800 - U+DFFF are reserved for surrogates only, so the function should returnUC_SURROGATEfor any UTF-16 surrogate codeunit. A non-surrogate codeunit has the same numeric value as its corresponding codepoint in the BMP (surrogates are only needed for codepoints outside the BMP), so the function would return something else.
This question already has answers here:printf with "%d" of numbers starting with 0 (ex "0102") giving unexpected answer (ex '"66")(4 answers)Closed8 years ago. I have a simple program. ``` #include <cstdio> int main() { int num = 000012345; printf("%d\n",num); return 0; } ``` The above program gives 5349. Why ? I mean it should be wrong, but why 5349 ?
Numbers starting with0are octal in c/c++. ``` Octal = 000012345 Decimal= 0×8⁸+0×8⁷+0×8⁶+0×8⁵+1×8⁴+2×8³+3×8²+4×8¹+5×8⁰ = 5349 Binary = 1010011100101 Hex = 14E5 ```
Suppose I have a variable date which is defined with extern in source code, i.e, extern date; then I want to assign a value to it at link time getting time from the computer on which it is compiled and assign to date variable. Is there a way to do that for example in gcc?
Are__TIME__and__DATE__what you are looking for ? If compiling and linking is one step in your scenario you can have your compiler and linker replace those macros with the date and time. If you compile one day and link the other this will not work because the compiler (better: preprocessor) decides which value is inserted. Have a look atthisor other posts here on stackoverflow.
``` #include<stdio.h> int main() { char arr[] = "abcdef"; char *ptr = arr; while(*ptr != '\0') ++*ptr++; printf("%s %s",arr,ptr); return 0; } ``` Output: bcdefg It is printing next alphabet of every alphabet given. What exactly is happening?
There are three operators here suffix++, prefix++, and indirection*. Suffix++has higher precedence that the other two and will be evaluated first. But when using suffix++, the value computation is sequenced before the side effect of updating the stored value, that is incrementing the pointer. So the pointerptrwill get incremented, but the value used in other two operands++and*, will be the old one. Prefix++and indirection operators have the same precedence, but are evaluated from right to left. So indirection*goes first and then prefix++increments the value of the object pointerptrpoints to.
i want to create somethink like this: ``` void funkcja(char *charTmp2){ asprintf(&charTmp2, "%i %.2f %s", 2, 3.20, "PIERWSZY"); } int main() { char *tmp; funkcja(tmp); printf("%s\n", tmp); } ``` I dont know why, there is no output. Please help me!
The problem is thatfunkcja()is only altering it's local copy of the pointer, try this ``` ssize_t funkcja(char **charTmp2) { return asprintf(charTmp2, "%i %.2f %s", 2, 3.20, "PIERWSZY"); } int main() { char *tmp; if (funkcja(&tmp) != -1) { printf("%s\n", tmp); free(tmp) } } ```
I like to round a floating number to nearest x.5. For example: ``` -3.64 -> -3.5 -3.12 -> -3.5 -2.90 -> -2.5 -0.45 -> -0.5 0.01 -> 0.5 7.65 -> 7.5 8.45 -> 8.5 9.63 -> 9.5 ``` Is there a decent way to implement it in C? Thanks. NOTE: I did NOT want to "round it to nearest half" !! Read the question and think before down vote please!!
What about doing a simplefloor(x) + 0.5? Should handle positive and negative values. If the numbers are exact integers they get rounded up to the next higher +0.5. ``` floor(0) + 0.5 = 0.5 floor(-1.2) + 0.5 = -1.5 floor(2.2) + 0.5 = 2.5 ``` Like @Stephen added in the comments usingceil(x) - 0.5instead would result in the same values except that exact integers get rounded down to the next lowest -0.5. i.e.: ``` ceil(0) - 0.5 = -0.5 ceil(-1.2) - 0.5 = -1.5 ceil(2.2) - 0.5 = 2.5 ```
I use a library which redefine the void type (among others): ``` #define XX_VOID void ``` So when I run doxygen on a code like ``` /** * @brief Function description */ XX_VOID foo(XX_VOID) { /*...*/ } ``` I get the warning ``` file.c:10: warning: return type of member foo is not documented ``` How can I tell Doxygen thatXX_VOIDis void so there is no return value ?
You can try with theMACRO_EXPANSIONtag: MACRO_EXPANSIONIf theMACRO_EXPANSIONtag is set toYES, doxygen will expand all macro names in the source code. If set toNO, only conditional compilation will be performed. Macro expansion can be done in a controlled way by settingEXPAND_ONLY_PREDEFtoYES.The default value is:NO.This tag requires that the tagENABLE_PREPROCESSINGis set toYES. WithMACRO_EXPANSIONset toYESthe result after doxygen preprocessing becomes: ``` void foo(void) { /* ... */ } ```
``` getint (int *); ``` I am not really sure what doesgetint (int *)mean? Can someone explain this?
This is a function prototype declaring the functiongetint(). The function takes as pointer to anintas a parameter. When prototyping a function it is not necessary to specify the parameters' names. The prototype is missing a return type, which for C then defaults toint. Omiting a return type however is violating the recent C standard, so code doing so could be considered invalid. An equivalent to ``` getint(int *); ``` though would be ``` int getint(int * pi); ```
``` unsigned char ticks_bits[3] = { 0x0F, 0x31, 0xC3}; __uint64_t ( * ticks ) () = (__uint64_t (*) ()) & ticks_bits; __uint64_t T = ticks(); // CRASH! ``` I have used this code for many years in Windows-32bit to get CPU ticks. But it will crash in Linux 64bit. Is there a way to make it work?
What I've done in the past is something like this: ``` uint64_t clock_ticks() { uint64_t ret; __asm__ volatile (".byte 0x0f, 0x31" : "=A" (ret)); return ret; } ```
I'm writing a program that calculates the roots of the quadratic equation. When I first wrote the code I didn't type a dot after 4 and 2 in the x equation and it didn't work! So what does that dot represent here and when should I use it? ``` #include<stdio.h> #include<conio.h> #include<math.h> int main() { int a, b, c; double x; scanf("%d %d %d", &a, &b, &c); x = (-b + sqrt(b*b-4.*a*c) ) / (2.*a); printf("%lf", x); getch(); return 0; } ```
4.is4.0 The decimal point makes it a float literal rather than an integer literal. The more important literal is2.as without it you would get integer division (and in most cases, the wrong result).
I was reading more about arrays vs pointers in C and wrote the following program. ``` #include <stdio.h> int arr[10] = { } ; typedef int (*type)[10] ; int main() { type val = &arr ; printf("Size is %lu\n", sizeof(val)) ; printf("Size of int is %lu\n", sizeof(int)) ; } ``` If, I execute this program, thensizeof(val)is given to be 8 andsizeof(int)is given to be 4. Ifvalis a pointer to the array with 10 elements, shouldn't it's size be 40. Why is thesizeof(val)8 ?
If val is a pointer to the array... Yes, it is, andsizeof(val)produces the size for the "pointerto the array", not the array itself. ...shouldn't it's size be 40.? No,sizeof(val)calculates the size of the operand, the "pointer" here. In your platform, the size of a pointer seems to be 64 bits, i.e., 8 bytes. So, it gives8. Also, as I mentioned, use%zuto printsize_t, the type produced bysizeofoperator.
I want to add systemcall to Linux kernel3.6.x. I have two filesmyheader.handmycode.c. As I have seen on some articles, I did the following: Create a folder from root directory/linux/myfolder.Create Makefile inmyfolderwith the rule:obj-y := mycode.oand I putmycode.cfile in this folder.I modify the main Makefile form the root directory.core-y := usr/ myfolder/ Where should I putmyheader.hand what rules should I have to add to the makefiles ? I tried putting it inside/linux/includebut it fails to compile.
You can have header file locally(within same directory as source file), and include it with simple#include "myheader.h".