question
stringlengths
25
894
answer
stringlengths
4
863
here is some code ``` class DengkleTryingToSleep{ public: int minDucks(int ducks[]); int temp(int ducks[]){ int size=sizeof(ducks); cout<<"sizeof="<<size<<"\n"; } }; int main (int argc, const char * argv[]) { DengkleTryingToSleep dt; int arr[]={9,3,6,4}; cout<<"sizeof "<<sizeof(arr); cout<<"\nsizeof from function ...
Because arrays decay to pointers when passed to a function. You're getting the size of a pointer in yourtempfunction. If you need to know the length of an array in a function ... you have to pass that in as well.
I was submitting a matrix exponentiation code in C language for finding the nth fibonacci and I was using long long int variable for storing the answer modulo 10000007 of nth fibonacci, and the judge was giving "time limit exceeded" but when I used "unsigned long long int" my code was accepted within the time and the ...
In order not to replicate anybody's effort, please seethis questionand thismore advanced question and answersof the same topic.dthorpe's answer inthis oneis highly detailed as well.wheaties' first commenthereis worth checking as a first trial.
I set up CDT for eclipse and wrote a simple hello world C program: ``` #include <stdio.h> int main(void){ puts("Hello, world."); return 0; } ``` The program builds and runs correctly, but eclipse keeps showing this yellow question mark by the side of inclusion statement that says"Unresolved inclusion: <stdi...
I found these answers (including the accepted one) somewhat cryptic. For me, I had to add the path where stdio.h is located (as @ardnew said). In Eclipse, you open the Properties of your project, expand "C/C++ General" and select "Paths and Symbols". Make sure you have added theincludedir for each language you are u...
When I run this code gcc gives me the output 10. Can someone explain to me why it gives me 10? :) ``` #include <stdio.h> int f(int x) { int y; y = 2*x; } int g() { int z; return z; } int main() { int x=5; f(x); printf("%d\n",g()); } ```
this is undefined behavior - you are referencing a variable which has no value set to it. likely, it gives 10 because the compiler has used the same memory location for the variable in f(), but there is no guarantee of that, it should not be depended on, and is nothing more than a curiosity.
Assuming that I have an variable like: ``` int n = 23; ``` it is possible split it, and convert to: ``` int x = n ?? ??; //2 int y = n ?? ??; //3 ``` have no idea how to do this. Any help is very appreciated. Thanks in advance.
It is not necessary to use bit operators for this. In fact, since bit operators work with thebinaryrepresentation of numbers, they're generally no good for base 10 calculations. ``` int n = 23; int x = n / 10; int y = n % 10; ```
What is the name ofgcc's intrinsic for comparing__m256and__m256i(AVX instruction set)?
As said in theIntel AVX documentation ``` _mm256_cmp_ps, _mm256_cmp_pd ``` etc Note that instead of having multiple comparison instructions, you have to pass an enum indicating the comparison done. E.g : ``` res = _mm256_cmp_ps(a,b, _CMP_LT_OQ); // AVX res = a < b ```
Under what circumstances (if any) would the signal SIGSTKFLT be synchronously raised by the kernel under Linux 3.0 on x86_64 ?
According toman 7 signal: ``` Signal Value Action Comment SIGSTKFLT -,16,- Term Stack fault on coprocessor (unused) ``` Since the x86 coprocessor stack cannot fault (I'm pretty sure), I don't think it can be signaled implicitly. Only explicit generation (bykill()orraise()) could cause it. Ig...
Given the following program: ``` #include <stdio.h> int main() { char buf[1024]; scanf("%s", buf); printf("----> %s", buf); return 0; } ``` which is executed as follows: grep ....| a.out or echo ....| a.out I get aSegmentation faulterror. Can anyone explain why?
Whatever you are echoing or grepping must contain more than 1023 characters. (1024 - 1 for the null terminator.) Instead of usingscanf, usefgetsand specify a size. Alternatively, usescanfbut specify the field length. You can doscanf("%1023s", buf);. If there's more bytes available, you can always do it again to read ...
I am implementing a version of merge sort in c. For the first step I have to split the array into sub-arrays. Is it bad practice to simply do this by having two pointers, one pointing to the start of the original array and the second pointing to the middle? Or should I malloc 2 new memory slots, copy the appropriat...
I don't think it's bad practice if you know what you're doing. In some cases, you sacrifice readability for efficiency. It's probably more clear if you'd just create two more arrays, but if you have a firm grasp on arrays and pointers, why allocate extra memory?
``` int i=5; f() { i++; i--; } ``` For the above code if three threads execute the above functionf()simultanously then what can be the total different values of global variableiare possible? Note :iis initialized to 5 globaly.
I would say that's an exercise in combinatorics, which I'm personally not going to do, however I do want to make clear that this isNOTthe correct way to have threads execute thisf(). The problem is that the implementation ofoperator++is not a single instruction, which means that halfway through one call tooperator++i...
Can anybody tell me how to make this C code work in C++ please? ``` uint64_t flv_dbl2int( double value ) { return (union {double f; uint64_t i;}){value}.i; } ``` I'm not precisely sure what is going on, is it bit shift?
As far as I can tell, the only legal strategy for type punning in C++ is throughmemcpy(), ie ``` uint64_t flv_dbl2int(double fvalue) { uint64_t ivalue; memcpy(&ivalue, &fvalue, sizeof ivalue); return ivalue; } ``` The straight-forward solution usingreinterpret_cast ``` uint64_t flv_dbl2int(double value)...
code one is: ``` int a = 0x42500000; float *f = (float *)&a; printf("%f", *f); //output 52.00000 ``` code two is: ``` int a = 0x42500000; float f = (float)a; printf("%f", f); //output 0.00000 ``` why code two output 0.00000,who can tell me why?
First snippet interprets the contents of the memory location ofaas if it were float,without casting. Unless you really know what you are doing, you don't want to do that, it's almost always a mistake. The second snippet casts the value ofato float, which should give you the same value as the int. It really does do th...
Is it considered as bad style to have a mixture of exact width types (introduced by C99) and standard C types in one prototype definition? E.g. ``` int some_func (uint32_t flags, int on_off_switch); ```
One generally uses an exact width type if the exact width is important to your code, for example if you absolutely need to know how many bits the representation of the integer will take up. It is certainly possible for some of the parameters to a function to have such constraints and others not to -- it all depends on...
I want to do something like this: ``` void* ptr = some_function(&ptr); ``` Is this legal in C?
Yes, it's totally legal. Beware that your some_function will need to have this signature : ``` void* some_function(void** param) ```
I have multiple threads running (pthreads api), each with it's own timer that calls a function handler(int signum) after a certain interval. As these threads call handler and within the function handler, how do I know which thread called it? Is thread-specific data required?
You can use thepthread_self()function to have the ID of the current thread.
``` int (*p)[2]; p=(int(*))malloc(sizeof(int[2])*100); ``` What is the right way to malloc a pointer to an array? I can't figure out the part with (int(*))
Posting comments as answer:InCyou should not to cast the return value ofmalloc. Please referthis poston SO for more information regarding why typecasting return value ofmallocis not a good idea inC. And if for some reason you really really want to cast, it should be(int(*)[2]).(int(*))isint *. The size passed to mallo...
I am new to C, and this typedef looks a little bit strange to me. Can someone explain what it does? ``` typedef void (*alpm_cb_log)(alpm_loglevel_t, const char *, va_list); ``` It is in a header file.
You can use cdecl.org :http://cdecl.ridiculousfish.com/?q=void+%28*alpm_cb_log%29%28alpm_loglevel_t%2C+const+char+*%2C+va_list%29+ It says: declare alpm_cb_log as pointer to function (alpm_loglevel_t, pointer to const char, va_list) returning void in this case, it is a typedef, not a declaration.
I have this in an exercise with pointers: ``` char *str = "Hello"; int count = 0; int len = 5; printf("%c\n", *(str + count)); printf("%c\n", *(str + len - count - 1)); *(str + count) = *(str + len - count - 1); ``` Both*(str + count)and*(str + len - count - 1)are valid values as theprintfs attest (I getHando). So w...
strpoints to a string literal which resides in memory where it is undefined behaviour to write to. Many times the compiler will put these string literals into memory with permissions that do not include write-permissions. This is why you're crashing. Change it to this: ``` char str[] = "Hello"; ``` This will create...
I have an application that prompt to user an character from user: ``` char letter; printf("Letter:\n"); scanf("%s", &letter); printf("ASCII code = %d\n", letter); ``` The problem is the accent that the user can write. if input isÁthe code above given ASCII code = -61 then I thought, if I turn it in an positive numbe...
%sis the format specifier for a C-string, and a character is only big enough to hold an empty C-string. Use%c, which is the format specifier for a single character.
How do you check if an opencv window has been closed? I would like to do: ``` cvNamedWindow("main", 1); while(!cvWindowIsClosed("main")) { cvShowImage("main", myImage); } ``` but these is no such cvWindowIsClosed(...) function!
What you are trying to do can be achieved withcvGetWindowHandle(): The function cvGetWindowHandle returns the native window handle (HWND in case of Win32 and GtkWidget in case of GTK+). [Qt Backend Only] qt-specific details: The function cvGetWindowHandle returns the native window handle inheriting from the Qt class ...
For a project, I have to detect a cube with a webcam. I think that OpenCV could be a good solution to find out where is it (real-time). I'm new in the computer vision domain, and I wonder which algo can I use ? Hough ? I've seen this video (quite impressive!):http://www.youtube.com/watch?v=ytvO2dijZ7ADo you know how h...
To get the result as in the video, you have given, you can usesquares.cppthat comes with OpenCV samples. (It is for images. Hope you can do it for videos.) Other useful SO on this topic are: 1)OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection 2)Square detection doesn't find squares
I have sent emails from windows using C# programminglike this. It is really an easy thing to do. However I have shifted to programming on linux a while ago and want some kind of equivalent for C/C++. I have been searching all the web and I can't find any library. All i find is application that I need to install and r...
There are a number of candidates show up when googling "C SMTP library", including a reference to this very bare-bones bit of code here on SO: https://stackoverflow.com/questions/58210/c-smtp-example
E.g. in Linux driver development one can find thecontainer_ofmacro. In essence it is the reverse operator to an->, yielding the pointer to the containing structure if you got a pointer to a member. Besides from Greg Kroah's blog I found this pattern in thelistandhashimplementation of Pintos.
The real name of this pattern is "container_of()." Attempting to fit this C-ism into a Java or C++ design pattern taxonomy is futile. The point is not to chain responsibility, or to designate or delegate anything. If you must think in these terms then it's a "messy generalized inheritance." If you don't have to think ...
Can any assumption be made on the order of entries in a directory stream obtained with theopendir()function? For example, are.and..always the first two entries? What would cause the order to change?
Posix says that you cannot rely on.and..being the first two entries. FromThe Open Group Base Specifications Issue 6: The directory entries for dot and dot-dot are optional. This volume of IEEE Std 1003.1-2001 does not provide a way to test a priori for their existence because an application that is portable must be ...
I am working on a platform, which doesn't have the math library, but I need to use thelogffunction (natural log with floating point input). I tried to search the code forlogfbut in vain. Can somebody provide or give a link forlogffunction code.
If you don't have math library, you can go to libc to look for the code -> http://sourceware.org/git/?p=glibc.git;a=blob;f=math/w_logf.c And see how logf calls __ieee754_logf -> http://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/ieee754/flt-32/e_logf.c I hope it helps you.
I have an ulong value, how can i convert it to LPTSTR? I need to get LPTSTR value. (no printf) Example code: ``` ULONG value = 1; LPTSTR valueString = ??? ``` Thanks!
Use one of the_itoa()family of functions orStringCchPrintf(). The links go to the 'safe' versions of the functions, but the winapi also provides 'unsafe' and leagacy variants.
Excuse me because I am a beginner in Java ... I want to translate the following code that I have done in C to Java: ``` #define ROWIMAGES 5 #define COLUMNIMAGES 11 typedef struct { int posX; int posY; int active; } image; image images[COLUMNIMAGES][ROWIMAGES]; ``` I'm trying to translate it as fol...
``` image[][] images = new image[COLUMNIMAGES][ROWIMAGES]; ```
This question already has answers here:What does '<<' mean in C?(5 answers)Closed10 years ago. I am reviewing some C code, and found a header file full of defines of the style: ``` #define BLABLABLABLA (1 << 2) #define XXXXXXXXXXXX (1 << 3) #define YYYYYYYYYYYY (1 << 4) ``` What do they mean? What do they do?
<< is the shift operator in C. So you define BLABLABLABLABLA by a zero value with a binary 1 shifted by 2 digits to the left. The resulting value is then : ...00000100 You would normally do this do mask things. So, say you have one status byte where every bit is a flag. And if the 3rd bit is set, this means BLABLABL...
``` pthread_t writeToFile = pthread_self (); unsigned short iterate; for (iterate = 0; iterate < 10000; iterate++) { fprintf (fp, " %d ", iterate, 4); fprintf (fp, " %lu ", writeToFile, sizeof (pthread_t)); fprintf (fp, "\n", writeToFile, 1); } ``` In main ()fp = ...
Let's take your firstfprintf:" %d ". it expects one argument (an int), but you give it two - iterate and 4. It seems like you are adding the size of the data, but you shouldn't. It should probably be: ``` fprintf (fp, " %d ", iterate); ``` In the other two sentences, it's not even clear what do you want to put in ...
I've ten ".o" files in a directory.i want to combine them as a shared lib (.so) file. For doing so,I am issuing following command ``` #gcc -shared *.o -o abc.so ``` but it throws following error message: ``` No command '-shared' found, did you mean: Command 'gshared' from package 'gshare' (universe) -shared: comma...
I agree with Chen Levy. It looks like gcc is either a stange version or not what you think it is. When I do: ``` gcc -shared *.o -o abc.so ``` I get the desired reponse. Try echo, or even: ``` which gcc ``` to try and see what's really going on. PS: I Tested on Ubuntu 10.10
the syntax for netif_napi_add is ``` netif_napi_add(struct net_device *dev, struct napi_struct *napi,int (*poll)(struct napi_struct *, int), int weight) ``` it is used for initializing the napi structure . the problem is when i am using the function as ``` netif_napi_add(wdev,rnapi,rrpoll(rnapi,20),16); ``` its gi...
In the call ``` netif_napi_add(wdev,rnapi,rrpoll(rnapi,20),16); ``` you arecallingrrpoll. It should be passed as a pointer: ``` netif_napi_add(wdev,rnapi,&rrpoll,16); ``` The system will then callrrpollfor you.
I am trying to write shell script to read the value from /sys/class/net/eth0/carrier but it's giving me the "permission denied" exception . The command I am trying to write in the shell script is ``` sudo echo $(/sys/class/net/eth0/carrier) ``` What I also noticed is that I am getting the same exception when I logge...
The syntax you have tries toexecutethat file. If you want to contents of the file in a variable, do something like this (probably bash-only syntax): ``` foo=$(</sys/class/net/eth0/carrier) ``` Or (portable) ``` foo=$(cat /sys/class/net/eth0/carrier) ``` If you just want to print it out tostdout: ``` cat /sys/clas...
In bash when I run a command likewc &orcat &that wants standard in right away, it returns immediately with [1]+ Stopped cat How is this accomplished? How do I stop a program that I started with exec, and how do I know to stop these programs in the first place? Is there some way to tell that these programs want stdin...
If you want spawned programs to behave similarly to how the shell works, callsetpgrp()after forking your child. This will cause the background program to run in its own process group, and therefore have a detached tty. When it tries to do I/O to the console, it will receive SIGTTIN or SIGTTOU signals. The default beha...
How might I write a single header file that defines an interface and use a separate source files to write platform-specific code? For example: ``` video.h video_windows.c video_linux.c video_osx.c ```
In your question you have all header files while you are talking about a shared header between source files. In any case you just provide a common.hfile and have 3 different ``` video_windows.c video_linux.c video_osx.c ``` You then include to your makefile (or whatever you use) the correct one according to the pla...
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed11 years ago.Improve this question I would like to know if there is any way to scan a text file and then run a command. I have tried grep getting nowhere. I ...
The following will cat all files that find finds that contain "needle" and will show their contents. Modify accordingly: find . -exec grep needle -q {} \; -exec cat {} \;
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed11 years ago.Improve this question I had the impression that there was a paper or article somewhere that claimed every sufficiently large project (not writte...
What Greenspun meant when he uttered this quip was that Lisp provides a great many foundational technologies for writing good software, and that programs written in other languages informally (and inferiorly) reproduce a number of them as they grow.
``` #define offsetof(type, member) ((size_t)(&((type *)0)->member)) ``` I am not understanding(&((type *)0)->member)what is this exactly telling me..... here type may be a structure or something else??... More specifically what is that 0 telling me here??
This is to determine the offset of a struct field. It works by using 0 as the address of the struct, then asking for the address of the field: ``` (type *)0 ``` is 0 as a pointer totype ``` &((type *)0)->member ``` is the address of that hypothetical struct'smembermember. If the address of the struct is 0, then ...
``` struct sniff_ip { struct in_addr ip_src, ip_dst; } function{ const struct sniff_ip *ip; ip = (struct sniff_ip*)(packet +SIZE_ETHERNET); } ``` My goal here is to change the values of ip_src and ip_dst, but I can't figure out the correct syntax to modify src or dst when it is in a struct within a struct. I know t...
You simply combine the operator in the correct places: ``` ip->ip_src.s_addr ```
Are their any bindings to use Cucumber with C? Google keeps telling me about vegetables when I ask.
It's possible to make Ruby bindings to a C application, but I haven't heard of any C binding for a Ruby application. It seems quite hard to make something like that. BTW,cucumber docslists all available ports and way to use their technology in an other langage. There is : Java Virtual Machine: JRuby and Java.NET (M...
I'm testing the perror function in C, and according tothis pageit prints a default message when a null pointer is passed: ``` int main(void) { int *p; perror(p); //crashes } ```
Causeint* pcontains a random/garbage value. It is not anNULLpointer. You need to explicitly initialize it withp = NULL;. Using an uninitialised variable is Undefined behaviour. main()also needs toreturn 0;.
How to create and bind socket using winsock2, which will be receiving only packets which use ipv6 protocol. Regards
Almost everything about network sockets and even windows specific stuff can be found atBeej's Guide to Network Programming. Transition from IPv4 to IPv6 is described in detailhere
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
TheEclipse CDTproject has a C parser written in Java, see myanswerto a similar question.
I plan to use mmap() to allocate a buffer close to a specific address. What I'm worried about is, the buffer allocated using mmap() will overlap other buffers allocated by malloc() or new operator (C++). Is it possible?
If you useMAP_FIXEDto demandmmapcreate the mapping at a particular address, thenyes it is possiblethat you overwrite an existing mapping such as space allocated bymalloc, part of a shared library's code or data section, etc. Basically it's always an error to useMAP_FIXEDunless you've already obtained the address range...
I'm using opendir function to check if a directory exists. The problem is that I'm using it on a massive loop and it's inflating the ram used by my app. What is the best (fastest) way to check if a directory exists in C? What is the best (fastest) way to create it if doesn't exists?
Consider usingstat.S_ISDIR(s.st_mode)will tell you if it's a directory. Sample: ``` #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> ... struct stat s; int err = stat("/path/to/possible_dir", &s); if(-1 == err) { if(ENOENT == errno) { /* does not exist */ } else { perror("sta...
could you tell my why the value of a referenced array and the value of the array itself has the same value? i know a is a type of int* but with &a it should be int** or am i wrong?? so the value should be a pointer to the a int pointer. example code: ``` #include &ltstdio.h> int main() { int a[10]; ...
Name of the array decays to an pointer to its first element in this case.
I am working on a platform, which doesn't have the math library, but I need to use thelogffunction (natural log with floating point input). I tried to search the code forlogfbut in vain. Can somebody provide or give a link forlogffunction code.
If you don't have math library, you can go to libc to look for the code -> http://sourceware.org/git/?p=glibc.git;a=blob;f=math/w_logf.c And see how logf calls __ieee754_logf -> http://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/ieee754/flt-32/e_logf.c I hope it helps you.
I have an ulong value, how can i convert it to LPTSTR? I need to get LPTSTR value. (no printf) Example code: ``` ULONG value = 1; LPTSTR valueString = ??? ``` Thanks!
Use one of the_itoa()family of functions orStringCchPrintf(). The links go to the 'safe' versions of the functions, but the winapi also provides 'unsafe' and leagacy variants.
Excuse me because I am a beginner in Java ... I want to translate the following code that I have done in C to Java: ``` #define ROWIMAGES 5 #define COLUMNIMAGES 11 typedef struct { int posX; int posY; int active; } image; image images[COLUMNIMAGES][ROWIMAGES]; ``` I'm trying to translate it as fol...
``` image[][] images = new image[COLUMNIMAGES][ROWIMAGES]; ```
This question already has answers here:What does '<<' mean in C?(5 answers)Closed10 years ago. I am reviewing some C code, and found a header file full of defines of the style: ``` #define BLABLABLABLA (1 << 2) #define XXXXXXXXXXXX (1 << 3) #define YYYYYYYYYYYY (1 << 4) ``` What do they mean? What do they do?
<< is the shift operator in C. So you define BLABLABLABLABLA by a zero value with a binary 1 shifted by 2 digits to the left. The resulting value is then : ...00000100 You would normally do this do mask things. So, say you have one status byte where every bit is a flag. And if the 3rd bit is set, this means BLABLABL...
``` pthread_t writeToFile = pthread_self (); unsigned short iterate; for (iterate = 0; iterate < 10000; iterate++) { fprintf (fp, " %d ", iterate, 4); fprintf (fp, " %lu ", writeToFile, sizeof (pthread_t)); fprintf (fp, "\n", writeToFile, 1); } ``` In main ()fp = ...
Let's take your firstfprintf:" %d ". it expects one argument (an int), but you give it two - iterate and 4. It seems like you are adding the size of the data, but you shouldn't. It should probably be: ``` fprintf (fp, " %d ", iterate); ``` In the other two sentences, it's not even clear what do you want to put in ...
I've ten ".o" files in a directory.i want to combine them as a shared lib (.so) file. For doing so,I am issuing following command ``` #gcc -shared *.o -o abc.so ``` but it throws following error message: ``` No command '-shared' found, did you mean: Command 'gshared' from package 'gshare' (universe) -shared: comma...
I agree with Chen Levy. It looks like gcc is either a stange version or not what you think it is. When I do: ``` gcc -shared *.o -o abc.so ``` I get the desired reponse. Try echo, or even: ``` which gcc ``` to try and see what's really going on. PS: I Tested on Ubuntu 10.10
Say I have a multi-digit integer in C. I want to break it up into single-digit integers. 123would turn into1,2, and3. How can I do this, especially if I don't know how many digits the integer has?
``` int value = 123; while (value > 0) { int digit = value % 10; // do something with digit value /= 10; } ```
I've made the follow signal handler ``` struct sigaction pipeIn; pipeIn.sa_handler = updateServer; sigemptyset(&pipeIn.sa_mask); sa.sa_flags = SA_RESTART; if(sigaction(SIGUSR1, &pipeIn, NULL) == -1){ printf("We have a problem, sigaction is not working.\n"); perror("\n"); exit(1); } ``` How do I re...
UseSIG_DFLin place of the function pointer when callingsigaction(2).
``` int i; i=0; for (i=0;i>2;i++) { repeat((3),"|",var); printf("\n"); } ``` For some reason it gets to the "for" and it skips it. I tried to put theint ioutside of the for and even initialized it outside of the for and in debug it is zero. all I need it to do is loop through this code tw...
Change: ``` for (i=0;i>2;i++) ``` to: ``` for (i=0;i<2;i++) ``` You're testing if it's> 2which will fail so it never enters the loop.
How can I get this function to change what x is pointing to in the following: ``` void test(const int *x) ```
``` void test(const int *x) { *((int *) x) = 42; } ``` But if your object pointed at isconst, you will invoke undefined behavior, like in: ``` const int bla = 58; test(&bla); // undefined behavior when the function is executed ``` This is ok: ``` int blop = 67; test(&blop); ``` You rather want to change the...
Referring to the Netfilter hook code at thispage The port to be checked against is declared as: ``` /* Port we want to drop packets on */ static const uint16_t port = 25; ``` The comparison is made as: ``` return (tcph->dest == port) ? NF_DROP : NF_ACCEPT; ``` In case variable port was of type int32, how can we c...
TCP ports are only 16 bit wide, so if yourport-variable contains anything outside the range 0..65535, something is wrong anyway. Also, you should usentohsto account for endianess differences. So I suggest something like: ``` BUG_ON(port < 0 || port > 65535); return (ntohs(tcph->dest) == (u16)port) ? NF_DROP : NF_AC...
I'm currently taking a computer security class and would like to try to port some of the class example exploits to my FreeBSD machine. For linux, I was able to disableASLRby using ``` "echo 0 > /proc/sys/kernel/randomize_va_space". Compiling with "-fno-stack-protector -z execstack" ``` flags ongccdisablesNXandcana...
There is no address space randomization feature on FreeBSD.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he...
UseInstruments. Open your project, go in the menu Product > Profile. This will openInstruments. TheTime Profilerinstrument is probably what you're looking for.
I want to convert the source & destination IP addresses from a packet captured using netfilter to char *. In my netfilter hook function, I have: ``` sock_buff = skb; // argument 2 of hook function // ip_header is struct iphdr* ip_header = (struct iphdr *)skb_network_header(sock_buff); // now how to convert ip_head...
The kernel's family ofprintf()functions has a special format specifier for IP-addresses (%pI4for IPv4-addresses,%pI6for IPv6). So with IPv4, you could use something like: ``` char source[16]; snprintf(source, 16, "%pI4", &ip_header->saddr); // Mind the &! ``` Or write to dynamically allocated memory. If you simply...
Suppose I have a nice comment block, such as the one below ``` /* ** This is a nice comment block. Displace the `**'s and I will eat your nose! Also, here is a long line of text clearly longer than the textwidth, which should force gq to rearrange the lines. Wheeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee...
See:help format-comments. I get the result you want from ``` :set comments=s0:/*,mb:**,ex:*/ ```
I create a raw socket to receive and forward on my machine which has two interfaces(eth0, eth1) bridged together. ``` socket(AF_PACKET, SOCK_RAW, 0xabcd); ``` My protocol will send some broadcast packets and I would like forward it on my own. How to disable forwarding my specific packets?
Sounds like you could use iptables / ebtables to stop the forwarding over the bridge and use libpcap in your program to pick up the packets/frames you would like to forward with your program. It might be kind of hackish, but libpcap can deliver just the packets you want to listen to, regardless of the machines firewa...
I have the following sample code: ``` uint64_t x, y; x = ~(0xF<<24); y = ~(0xFF<<24); ``` The result would be: ``` x=0xfffffffff0ffffff y=0xfffff ``` Can anyone explain the difference? Why x is calculated over 64 bit and y only on 32?
The default operation is 32 bit. ``` x=~(0xf<<24); ``` This code could be disassembled into the following steps: ``` int32_t a; a=0x0000000f; a<<=24; // a=0x0f000000; a=~a; // a=0xf0ffffff; x=(uint64_t)a; // x = 0xfffffffff0ffffff; ``` And, ``` y = ~(0xFF<<24); int32_t a; a=0x000000ff; a<<=24; // a=0xff...
I have compiled a program from my Ububtu 10.10 terminal by gcc file_name.c -o new_file command. It compiled successfully creating an executable file named new_file. But when I was trying to execute it by this command ``` ./new_file ``` It says that permission is denied of new_file. I've checked the permission prop...
You have to give it exe. permissions. So:chmod +x new_file When you create a new file with your gcc, by default, this isn't executable. So, you have to gave it permissions of execution. Withchmod(see this)you change permissions on file. In that specific case, you gave execution permissions ( + [plus] means gave, '...
I have a project which uses Bluetooth 2.1 code and We want to migrate to 3.0 code in c programming. Questions: How to migrate from 2.0 to 3.1 or possibly 4.0 in term of writing code?Is there any tutorial or link which describes how to change the code that accept bluetooth 3.1 code?Also I am wondering do I need to ch...
The main change in Bluetooth 3.0 added the ability to use co-located wifi hardware to send data at higher rates (but it goes over the wifi link, not the bluetooth link). This is mostly a hardware / firmware change, and I don't think it's very commonly used. Bluetooth 4.0 adds a completely different low energy mode t...
I know it sounds a little stupid but is there a way to prove that on Windows: fopenfunction calls winapi function CreateFile (or CreateFileEx)freadfunction calls winapi function ReadFile (or ReadFileEx) If there is a more general way to determine how some C library functions call the winapi functions, I'm also happy...
Visual C comes with the source code for the C runtime library. Would that settle things?
I am wondering if it is possible to generate compiler warnings or errors for specific library functions. For example, I work all the time on multithreaded programs and I would like to get a compiler warning whenever I try to use a not-threadsafe function like strtok (instead of strtok_r). Thanks.
You want to use the poison pragma:http://gcc.gnu.org/onlinedocs/gcc-3.2/cpp/Pragmas.html ``` #pragma GCC poison strtok ```
I'm heaving an (big) array of floats, each float takes 4 bytes. Is there a way, given the fact that my floats arerangedbetween 0 and 255, to store each float inlessthan 4 bytes? I can do any amount of computation on the whole array. I'm using C.
How much precision do you need? You can store each float in 2 bytes by representing it as anunsigned short(ranges from 0 to 65,535) and dividing all values by2^8when you need the actual value. This is essentially the same as using a fixed point format instead of floating point. Your precision is limited to1.0 / (2^8...
This question already has answers here:Closed11 years ago. Possible Duplicate:How does XOR variable swapping work?Swap the values of two variables without using third variable How can I write a C code to swap 2 integer variables without using any extra variable?
``` a = a^b; b = a^b; a = a^b; ``` use XOR ( ^ ) operatoryou can do it with adding: ``` x = x + y; y = x - y; x = x - y; ``` but I think XOR is the best way because it's faster.This is a bitwise operator like&and|.1^1 == 00^0 == 01^0 == 10^1 == 1You can readthisfor more information
``` // Works int fnamesize=0; fnamesize=message[0]<<24; fnamesize+=message[1]<<16; fnamesize+=message[2]<<8; fnamesize+=message[3]; // Doesn't work int fsize; memcpy(&fsize,message,sizeof(int)); ``` Can someone explain why the second one doesn't work? The memory I'm copying from,messageis achar *. Wh...
That's because ofendianess, which means the layout of bytes in an int. In windows, the second way will give you an int that has the opposite byte order, like this: ``` fsize=message[3]<<24; fsize+=message[2]<<16; fsize+=message[1]<<8; fsize+=message[0]; ```
I'm looking for a way to implement RPC between Java and C. What are the options to do this? Best Wishes p.s I have web java application which is hosted on Glassfish server and C daemon. I need to directly call functions from bought sides.
The whole point of RPC is to let two opaque processes on different systems talk to each other over a network. The languages used are irrelevant, except that you have to learn the corresponding RPC libraries for both languages.
I am trying to concat two const char * strings. When i have a statement likestrcat(a,b)I get the warningexpected ‘char * restrict’ but argument is of type ‘const char *’ is there a way to call strcat that will not produce the warning? Thanks!
strcat()modifies the first operand. Therefore it cannot beconst. But you passed it aconst char*. So you can't usestrcat()on twoconst *charstrings.
I'm writing a program in C in which the server listens on a well known port, waits for client to connect, and then creates a random port for the client to use and send this port number back to the client. My main difficulty is how to create a "random" port. Should I just be using srand and create a random 4 digit port...
Binding port 0 is the solution. It gives you an arbitrary port, not a random port, but this is what many applications do (e.g. FTP etc). After binding, you can usegetsocknameto figure out which port you got.
So I am trying to use the following code to add some memory to the heap without using malloc (size is a unsigned int parameter in the function, and is not a set number) ``` void * temp = sbrk(sizeof(void*)+sizeof(unsigned int)+size); ``` Now I want to set the value of the void * in temp to be NULL, however when I tr...
If you want to change the value oftemp, usetemp=NULL. If you want to putNULLin the address thattemppoints to, use*(void**)temp=NULL.
gtk define IO callback as bool func(gtkchannel, GIOCondition,GPointer userdata) the problem is that I want to send 2 arguments as a user_data: widget and a pointer that will keep my errors form the callback. I know that I can send struct but I want to check if there is another way to do it. is there a way to edit th...
You have to use a struct, or make your own class and pass that. Alternatively, use GTK from Python or Vala. Passing data to callbacks is much easier in those languages.
I've found this snippet on a website : ``` #define DISPLAY_CR (*(volatile unsigned int *) 0x4000000) DISPLAY_CR = somevalue; ``` that is supposed to describe DISPLAY_CR as a volatile unsigned int pointer to the adress 0x4000000 What I don't understand is why : the double parenthesis imbrication ?the two stars us...
The extra parentheses are standard practice in macros. Macros are expanded in copy-and-paste fashion, so without the parentheses, theprecedencemay be altered depending on the context. Ignoring the extra parentheses, your code expands to: ``` *(volatile unsigned int *) 0x4000000 = somevalue; ``` which is equivalent...
In linux kernel how to mapblock_devicetodevicestruct? In other words if we have ablock_devicestruct how we can get correspondingdevicestruct?...
It appears that shortest way for me is to findbdev_mappointer and perform akobj_lookup(bdev_map, inode->i_rdev, &dummy)operation. This returns akobjectthat correspons to block device (i_rdev).
I have a very simple question, but I have not managed to find any answers to it all weekend. I am using thesendto()function and it is returning error code 14: EFAULT. The man pages describe it as: ``` "An invalid user space address was specified for an argument." ``` I was convinced that this was talking about the I...
EFAULTIt happen if the memory address of some argument passed tosendto(or more generally to any system call) is invalid. Think of it as a sort ofSIGSEGVin kernel land regarding your syscall. For instance, if you pass a null or invalid buffer pointer (for reading, writing, sending, recieving...), you get that Seeerrno...
I'm curious to know how one can implement theeffect demonstrated hereusing OpenCV. I think it's some sort of displacement map filter but I'm not 100% sure. After that page has fully loaded, move the mouse around to see the background image move (it's the effect I'm looking for). Is it possible? How would I go about ...
It's been almost 2 years since I've asked this question and I think it's time to answer it: the source code that implements this filter using OpenCV can be found in myGitHub repo. The implementation is based on the documentation ofAdobe Flash DisplacementMapFilter. There's another tutorial I recommend people to read...
I am writing a small tool in which I require to find per-user File-system-memory-usage. I have to do some clean up activity if file-system usage is crossing certain threshold value. What is the system call that I can use, so that I could be able to find per user memory usage?
A simplistic approach would be ``` du -shc /home/* ``` To sort it: ``` du -smc /home/* | sort -n ``` There is also a wellknown Perl script that has the option of mailing disk usage reports per user:durep http://www.ubuntugeek.com/create-disk-usage-reports-with-durep.html
It seems ANSI C 89 is the best choise for writing a cross-platform library because many platforms (Windows, Unix, Linux, Mac, Android, ...) supports it. But is there any platform that not supports ANSI C 89? I am not sure about J2ME, iPhone and so on..
First, ANSI C usually refers to C89, so the C89 is redundant. iOS supports ANSI C, as well as most of the platforms. J2ME is a Java platform and by default it does not support C at all. The main platforms all support ANSI C, but there are some embedded platforms that does not. I don't think you should be worried abo...
I am working on a project and I wrote two C programs that convert date and time into minutes and then back. What I want to do is pass a php variable into a C program and then have the C program return the result to a variable in php. I realize that you can use popen or exec commands but I am unsure how to use these c...
``` $cmd = "/path/to/prog " . escapeshellarg($something); $c_output = shell_exec($cmd); ```
This question already has answers here:Post-increment on a dereferenced pointer?(13 answers)Closed9 years ago. I'm not really sure what the order here is. Is it: 1) Dereference the value of pointer p after increasing it 2) Dereference the value of pointer p before increasing it
There is no ordering between the increment and the dereference. However, the*operator applies to the result ofp++, which is the original value ofpprior to the increment.
I'm working on an assignment to write a program mirroringac(1). The output ofacand myaacare both: ``` " total 5.80\n" ``` I ranaac -file xyz > out1andac -file xyz > out2 However, when usingdiff out1andout2I get: ``` 1c1 < total 5.80 --- > total 5.80 ``` Getting the hex cod...
Seean ASCII tableand note that011is tab, whereas you are using040spaces.
I have a problem with reading the EOF character for the last input in C ``` j=0; while(*(name2+j)!='\n'){ if(*(name2+j) == ' '){ j++; continue; } d[tolower(*(name2+j))]++; j++; } ``` For the last input, there is no new line character, the value of j is getting set to very large...
EOFis an integer value outside the range of achar(since its very purpose is to indicate thatnocharis present), so if you want to be able to compare a value toEOF, then you need to retrieve and store that value as anintrather than as achar.
Assume the following is a 2d array that we are operating on ``` a b c d e f g h i j k l m n o p ``` The surrounding neighbor of 'f' are [a b c e g i j k]. I'm trying to create a cache friendly data structure to store the neighbor of a node. Right now I have something like so ``` struct Neighbor{ size_t neighborP...
Every cell has the same neighbors, in terms of their relative location, except for the edge cells. But if you add a border (an extra row & column at the start and end), and fill it with a value that lets you know it is a border, the you don't need any data structure at all to identify neighbors.
How do I convert timeval to time_t? I'm trying to convert: umtp->ut_tv to a time_t so I can use a difftime(a,b). ``` struct { int32_t tv_sec; /* Seconds */ int32_t tv_usec; /* Microseconds */ } ut_tv; /* Time entry was made */ struct timeval ut_tv; /* Time ent...
time_tjust stores seconds, so ``` time_t time = (time_t)ut_tv.tv_sec; ``` Should work, but since you're just looking for a difference, there's always the magic ofsubtraction. ``` struct timeval diff = {a.tv_sec-b.tv_sec, a.tv_usec-b.tv_usec}; ``` This lets you keep all the precision you had before.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
As for a compiler, I would recommend MinGW.
This question already has answers here:Closed11 years ago. Possible Duplicate:getting segmentation fault in a small c program Here's my code: ``` char *const p1 = "john"; p1[2] = 'z'; //crashes printf("%s\n", p1); ``` I know p1 is a "read-only" variable, but I thought I could still modify the string ("john" ). ...
You cannot safely modify string literals, even if the pointer doesn't lookconst. They will often be allocated in read-only memory, hence your crashes - and when they're not in read-only memory modifying them can have unexpected consequences. If you copy to an array this should work: ``` char tmp[] = "john"; char *co...
i wrote a small prog : ``` 1 #include<stdio.h> 2 main(){ 3 char* str = "string"; 4 *str = 'k'; 5 printf("string is = %s\n",str); 6 } ``` This program gets compiled without any error or warnings, but when i run it, it gives segmentation fault. While if i rewrite the 3rd line ...
``` char* str = "string"; ``` This puts the string in read-only memory. It is undefined behavior (usually unpleasant behavior) when you try to modify it with the next line. Try something like ``` char str[] = "string"; ``` instead.
Consider the following C function.Does opening the braces to create a local scope make compilers create a record on the stack to mantain the variables declared in the scope ? ``` void function() { int q,r; ... { int i = 0; int j = 3; q = j + 1; } ... } ``` If so...
The arrangement of the stack is not specified by the C standard. Curly braces ({}) introduce a new scope, so in principle, yes, this could create a new frame on the stack. But the compiler may choose to optimise this overhead away.
I am programming an AVR microcontroller, and in the programmers notepad in the WINAVR Suite. I am trying to seperate my code, however the sepeaet .c file I am unable to use AVR pre-defined variables. (the variables AVR supplies to point to certain BITs) for example, this code will work in my main.c file. but not in ...
You have to includeavr/io.hin your projet and also specify the mcu in thegcccompiler command line with-mmcu=option.
Is the concept of the Fortran ISO_C_BINDING module also supported by C/C++ compiler vendors? For example, the size of a C/C++intcan vary between the compilers from different vendors. So, with the ISO_C_BINDING module, we know that a FortranC_INTtype is 4 bytes; rather than merely having akindof 4. But, we still don't ...
As far as I know, the standard only demands matching types in the same toolchain. Thus you are better using the C-Compiler from the same vendor. The standard doesn't claim anything about the sizes of the C_ kinds, I think. Edit: Just looked it up in the standard, it is always talking about the companion C-compiler.
I have implemented a chat server in C/Linux that uses TCP sockets. It is currently using a single process and uses select() to keep the server from blocking. I've read that select() is a pretty slow method and I'm looking to upgrade the server to a more efficient version. I'm currently looking at libevent but I was h...
For Linux (only) you can use epoll, which is faster in most cases (but not all). The main disadvantage of epoll is that it is supported on the Linux OS only (not portable). In a summary note, epoll can monitor a very large number of descriptors and will return a list ofonlythose that changed (no need to pass over al...
I want to build a string label with a changing suffix. This is to take place within a for-loop. (The suffix being the value that is looped through). This is how I'd do it in C - is there a more c++-ish way to do this? ``` for (int i = 0; i<10; i++) { char label[256]; sprintf(label, "Label_no_%d", i); //...
You can use stringstreams: ``` for (int i = 0; i<10; i++) { std::ostringstream label; label << "Label_no_" << i; // use label.str() to get the string it built } ``` These let you useoperator<<, exactly like you would forstd::coutor a file, but writing to an in memory string instead. Or alternatively y...
I've declared the following array of strings: char *arrayIndices[100] = {0}; I do a comparison with recp->ut_line which is declared as: ``` struct utmp { .... char ut_line[32] } ``` using: ``` strcmp(arrayIndices[i], (char*)recp->ut_line)) ``` This gives me a segmentation error. I've also tried these in gdb: ```...
You need to use apostrophes, not quotes, here: if (arrayIndices[i] == '\0')
If I have an objectatype objwhereatypeis defined liketypedef struct myType {...} * atype, is there any way I can get all the references toobj, or at least how many there are? Something like: ``` atype obj; ... // Allocate aStruct a; a.obj = obj; aStruct b; b.obj = obj; int refs = get_references(obj); // refs shou...
No, there's no implicit way. But you could implement areffunction that automatically increases a counter, and anunreffunction to decrement it. ``` a.obj = ref(obj); /* ... */ a.obj = something_else; unref(obj); ``` And that counter can be something external to any of thestructs. For example, you could use a hash ta...
I Created a toolbar resource (IDR_TOOLBAR) using resource editor, how can I add it to a window using basic Win32 APIs?
There is no "Toolbar resource" thing for WIN32 API. Toolbar resources are artifacts for MFC classes likeCToolbarand the like. It actually consist in a bitmap (contaning the stripe of the images, and having the same ID of the toolbar) and aRT_TOOLBAR(actuallyMAKEINTRESOURCE(241)) resource type that is a linear vector ...
I keep getting this error mesage when trying to add a breakpoint in gdb. I've used these commands to compile: ``` gcc -g main.c utmpib2.c -o main.o and: cc -g main.c utmpib2.c -o main.o and also: g++ -g main.c utmpib2.c -o main.o ``` I also tried "-ggdb" instead of "-g" and I still get that error message. I then e...
You have to add extra parameter -g, which generates source level debug information. It will look like: ``` gcc -g prog.c ``` After that you can use gdb in common way.
I am working with a Hashtable struct that maps keys to values, where the values are (void *) so that Hashtables can hold any kind of value. To be able to free those values, the deconstructor of a Hashtable takes in a pointer to a freeing function as an argument. In my case, I know I am going to be freeing basic types...
You can (and should) pass tofreeevery pointer that has returned bymalloc, no matter which type (or struct) it points to. Be careful tonotpass tofreepointers that you didn't get from malloc. (Middle of arrays, local variables, etc) BTW, unless some of your data types need some work before freeing, you can do it withou...
I'm trying to declare an array of pointers of astructsome_structin C Can I do: ``` some_struct* arr[10]; ``` instead of: ``` some_struct** arr=(some_struct**)malloc(10*sizeof(some_struct*)); ``` And what's the difference?
The first one puts the array on the stack.The second one allocates it on the heap. In the first case, the lifetime of the array is only the scope at which it is defined in. When it falls out of scope, it will be freed automatically so you don't have to do any clean up. In the second case, the array lives beyond the...