question
stringlengths
25
894
answer
stringlengths
4
863
Until recently, I thought CPU caches (at least, some levels) were 4kb in size, so grouping my allocations into 4kb slabs seemed like a good idea, to improve cache locality. However, readingLine size of L1 and L2 cachesI see that all levels of CPU cache lines are 64 bytes, not 4kb. Does this mean my 4kb slabs are useless, and I should just go back to using regular malloc? Thanks!
4KB does have a significance: it is a common page size for your operating system, and thus for entries in your TLB. Memory-mapped files, swap space, kernel I/Os (write to file, or socket) will operate on this page size even if you're using only 64 bytes of the page. For this reason, it can still be somewhat advantageous to use page-sized pools.
I'm trying to match strings like this:"labels": [{"name": "labelname"where labelname can contain any amount of letters, numbers or whitespaces. I tried"labels": \[\{"name": "(.*?)",which works in regex101.com but i dont get any matches using the posix regex.h. If i do"labels": \[\{"name": "it matches the string up to the fist"
Just do a class that select everything apart from the closing character, like that : ``` "labels": \[\{"name": "([^"]*)" ```
I get an error "conflicting types for 'abs' in my function. The code is very simple. ``` double abs (double x) { // Returns absolute value if (x<0) return (x*(-1)); else return x; } ``` This is on a C proyect on codeblocks. I already tried casting the returns but the error remains anyway.
My guess is you have<stdlib.h>included becauseabsis already declared there and has the signatureint abs(int), so your definition produces "conflicting types".
If condition inside thefindsetis not giving correct comparison. It is always shows not equal. Where did I make a mistake? ``` #include<stdio.h> struct node { struct node *p; int rank; }; void makeset(struct node x) { x.p = &x; x.rank = 0; } void findset(struct node x) { if (x.p == &x) { printf("It worked bro\n"); } } int main() { int nv, ne; nv = 4; ne = 5; for (int i = 0; i < nv; ++i) { struct node i; makeset(i); findset(i); } } ```
``` void findset(struct node x) { if (x.p == &x) { ``` thatxis a copy of the one passed in... x is always brand new and&xwont match any previous address. Note that this is true not just of structs but all values... ``` int i = 3; void f( int j) { // &j != &i // j == i // j and I have the same value, but different address } int main() { f(i); } ```
Everyone knows theabs()function togetthe absolute value of variables. Is there a similar function or efficient way of setting it ignoring the sign? Practical example:Force minimum value for motor speed control ``` if (abs(speed) < 50 && speed != 0) { if (speed < 0) speed = -50; else speed = 50; } ``` I am looking for a standardized function or a clever bit manipulation one-liner. Wrapping the above if into a function or macro is obvious.
It's basically thesignumfunction ``` speed = 50*sgn(speed); ``` There's astandard functionfor this ``` speed = copysign(50, speed); ``` however this isn't quite efficient for integer types. Thesgn()function can be implemented using various other ways that you can findhere ``` speed = ((speed > 0) - (speed < 0))*50; ```
A weird interview question I had yesterday Given avoid *ppointer, and a inta = 1;how to dereference to any level pointers? For example, if input is 1, then you can get the data by*(int *)p if input is 2, then you can get the data by**(int **)p if input is 3, then you can get the data by***(int ***)p but what if the input isn? how can you get the data by*xN(int *xN)p? I completely had no idea.
Something like this: ``` int dereference(void *p, int n) { for (int i = 0; i < n; i++) { p = *((void **) p); } return (int)p; } ```
Everyone knows theabs()function togetthe absolute value of variables. Is there a similar function or efficient way of setting it ignoring the sign? Practical example:Force minimum value for motor speed control ``` if (abs(speed) < 50 && speed != 0) { if (speed < 0) speed = -50; else speed = 50; } ``` I am looking for a standardized function or a clever bit manipulation one-liner. Wrapping the above if into a function or macro is obvious.
It's basically thesignumfunction ``` speed = 50*sgn(speed); ``` There's astandard functionfor this ``` speed = copysign(50, speed); ``` however this isn't quite efficient for integer types. Thesgn()function can be implemented using various other ways that you can findhere ``` speed = ((speed > 0) - (speed < 0))*50; ```
A weird interview question I had yesterday Given avoid *ppointer, and a inta = 1;how to dereference to any level pointers? For example, if input is 1, then you can get the data by*(int *)p if input is 2, then you can get the data by**(int **)p if input is 3, then you can get the data by***(int ***)p but what if the input isn? how can you get the data by*xN(int *xN)p? I completely had no idea.
Something like this: ``` int dereference(void *p, int n) { for (int i = 0; i < n; i++) { p = *((void **) p); } return (int)p; } ```
This question already has answers here:simple c program keeps crashing(2 answers)Closed5 years ago. I was trying to show alternating series usingifstatement nested in awhileloop. That's the code. ``` main() { printf( "Enter a number: " ); int n1; scanf( " %d", n1 ); int temp = 1; while( temp <= n1 ) { if( temp % 2 == 0 ) { printf(" %d", -1 * temp ); temp++; } else { printf( " %d", temp ); temp++; } } } ``` The compiler does not show any error, but while the program is running it says that it stopped working. Any suggestions?
You need to providescanf()with the address of the variable you are assigning to, use the address-of operator&: ``` scanf(" %d", &n1); ```
I'm not sure why this is happening but I am getting a "Segmentation fault (core dumped)" from this very simple code. Any ideas as to why? I have to use a string to tell fopen() what file to open. ``` #include <stdio.h> #include <string.h> int main(void) { char *small = "small.ppm"; FILE * fp; char word[5]; fp = fopen(small, "r"); fscanf(fp, "%s", word); printf("%s\n", word); return 0; } ```
If the file does not existfpwill be NULL and sofscanf(fp, ...)will segfault. It's important to check all file operations for success. The usual pattern goes something like... ``` FILE *fp = fopen(filename, "r"); if( fp == NULL ) { fprintf(stderr, "Couldn't open %s: %s\n", filename, strerror(errno)); exit(1); } ```
I am getting the following compilation error:request for member ‘threeds’ in something not a structure or union here is my struct: ``` struct pthread_arg { int size; int threeds; int the_threads; }; ``` Here is the line causing the issue: ``` int first = *(arg.threeds) * N/number_of_the_threads; ``` I have looked at other similar questions on here, but still got the same error after making the changes suggested.
It appearsargis an arugment passed to a thread function (which is a pointer to your struct). In that case, you can't directly dereferenceargbecause it's avoid*. Convert it to appropriate type (which must match the argument passed to pthread_create API) and then use: ``` void *multiplication(void *arg) { struct pthread_arg *myarg = arg; int first = myarg->threeds * N/number_of_the_threads; ... ```
I am getting the following compilation error:request for member ‘threeds’ in something not a structure or union here is my struct: ``` struct pthread_arg { int size; int threeds; int the_threads; }; ``` Here is the line causing the issue: ``` int first = *(arg.threeds) * N/number_of_the_threads; ``` I have looked at other similar questions on here, but still got the same error after making the changes suggested.
It appearsargis an arugment passed to a thread function (which is a pointer to your struct). In that case, you can't directly dereferenceargbecause it's avoid*. Convert it to appropriate type (which must match the argument passed to pthread_create API) and then use: ``` void *multiplication(void *arg) { struct pthread_arg *myarg = arg; int first = myarg->threeds * N/number_of_the_threads; ... ```
I'm using the Bochs emulator and for my class we're using gcc 4.2.1. I believe I've gotten Bochs running, but now I need to compile our programs which are compatible with gcc 4.2/.1. I understand OSX uses an alias for gcc 4.2.1, but how can I use gcc specifically and not clang? Edit: GCC 4.6.3 not 4.2.1 sorry
You can install previous version of gcc pretty easily usinghomebrew. If you have homebrew installed you can get gcc 4.9 by running ``` brew install [email protected] ``` After it is installedgccwill still map to the clang that came with your mac. The newly installedgccwill be installed at/usr/local/binand be called something likegcc-4. You can find the exact executable name using ls /usr/local/bin | grep gcc Hopefully 4.9 is close enough to 4.6 for your purposes.
Consigne: each integer is in the inclusive range 1 - 109. I use variable with the typeunsigned long long int Is it enough for the stated range?
10^9 is way smaller than 2^32 So in your case, no need to useunsigned long long(it fits, yes), which is overkill and can lead to slower operation. Use the proper type, normalized instdint.hinclude:uint32_toruint_least32_t(uint32_t vs uint_fast32_t vs uint_least32_t) longis also guaranteed to beat least 32 bits, so it's a good & simple choice as well.
I am using theEVP high-level functions in OpenSSL. I haven't found any examples online showing how to use these functions (e.g.EVP_EncryptInit_ex(),EVP_EncryptUpdate(),EVP_EncryptFinal_ex()) to encrypt data using an RSA public key. Specifically, I do not see aEVP_CIPHERtype that matches RSA, similar to what you see for AES like:const EVP_CIPHER *EVP_aes_128_cbc(void);inevp.h. I think one for RSA is required to initialize EVP for encryption using that method. Can anyone help me understand how to use an RSA existing key to encrypt data using OpenSSL's EVP routines? Examples would beextremelyhelpful.
To do asymmetric encryption you need to use different EVP routines than for symmetric crypto. In particular see the EVP_PKEY_encrypt() function. The man page is here, and it contains an example. https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_encrypt.html
What will happen in below case?What will happen if I writeif (p == NULL) { break; }?#include <stdio.h> void main() { int *p; while (1) { p = malloc(1024); // allocating memory in infinite while loop // if (p == NULL) { break; } } }
You might expect to run out of memory eventually, andmallocmust returnNULLin that case. But note that some C runtime libraries and operating systems will not actually allocate the memory until you use it. Since you're not using the memory, you might find that the loops runs forever, but not due to the explicit failure ofmalloc.Inclusion of theifstatement will end the program ifmallocfails to allocate. If the C runtime libary and operating system are behaving in the way I've mentioned, thenmallocmay well never fail to allocate and your programcouldloop infinitelydespitetheifconditional.
I am trying to use JNI to integrate a .C code with my Java project. While trying to generate the .dll file using vcvars32.bat in visual studio 2017 it gives me an error message tells: "C:\Program Files\Java\jdk1.8.0_151\include\jni.h(39): fatal error C1083: Cannot open include file: 'stdio.h': No such file or directory" I removed the including of stdio.h library in my C code but it didn't help. My command is: "cl -I"C:\Program Files\Java\jdk1.8.0_151\include" -I"C:\Program Files\Java\jdk1.8.0_151\include\win32" -LD "Factorial.c" -Fe"Factorial.dll""
After sometime of searching and failing I had to generate it by VS13 vsvars32.bat note that vsvars not VS17's vcvars that generated 32-bit dll and because my platform is 64-bit I had to install and switch to 32-bit JVM and problem is resolved.
I'm running onOSXand trying to compile following c code to webAssembly: ``` void test(){ //do stuff } ``` I've looked atthis exampleand tried running the following commands: ``` clang -emit-llvm --target=wasm32 -Oz test.c -c -o test.bc llc -asm-verbose=false -o test.s test.bc ``` First command works fine and clang generates the .bc file, but when I try to run the second command I get:llc: : error: unable to get target for 'wasm32', see --version and --triple. Any help would be appreciated.
It looks like your version of llvm was not compiled with support for the WebAssembly backend. This backend is still experimental so you need to enable it at cmake time with:-DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=WebAssembly
This question already has answers here:printf anomaly after "fork()"(3 answers)Closed5 years ago. So as far as i know fork creates a duplicate of the process it's called from but it also copy's it's program counter so it continues from the line after it's called but why is this code printing hello world twice when it's before the fork ``` #include <stdio.h> #include <sys/wait.h> int main() { printf("Hello World"); fork(); wait(NULL); return 0; } ```
printfdoesn't actually print -- it actually just puts data into a buffer to be printed later. It will actually be printed when the buffer gets flushed, which can happen in a variety of ways. In your case, the buffer flush doesn't happen until after the fork, so both the parent and the child have a copy of the string to be printed in the buffer when they fork, and both end up printing it.
I'm trying to figure out the correct way to pass database connection parameters to this libpq connection control function. PQconnectdbParams ``` PGconn *PQconnectdbParams(const char * const *keywords, const char * const *values, int expand_dbname); ```
Fromthe documentation: This function opens a new database connection using the parameters taken from two NULL-terminated arrays. The first, keywords, is defined as an array of strings, each one being a key word. The second, values, gives the value for each key word. I have never used this function in practice (asPQconnectdb()seems simpler), but this example should work I think: ``` char *keywords[] = {"hostaddr", "port", "dbname", 0}; char *values[] = {"127.0.0.1", "5432", "testdb", 0}; conn = PQconnectdbParams((const char **)keywords, (const char **)values, 0); ```
I have a structure defined as ``` struct Bod{ int x, y; }; ``` Then I have a function ``` void add(struct Bod* s) { h[++nh] = s; } ``` And in next function, I tried to pass array into the previous function, which gives me errorIncompatible type for argument 1 of function add() ``` void bfs(struct Bod* body, int start_index){ struct Bod* v; add(body[start_index]); ... } ``` And in main, I have created this array of struct like this ``` struct Bod body[m*n]; ``` What did I miss?
Sincebody[start_index]gives youoneelement ofbodyat indexstart_index, you end up passing in that single element toadd(). If you want to pass in the array itself, you just need to pass inbodyas-is: ``` add(body); ``` Or, to pass in the array starting at a given index: ``` add(&body[start_index]); ```
This question already has answers here:printf anomaly after "fork()"(3 answers)Closed5 years ago. So as far as i know fork creates a duplicate of the process it's called from but it also copy's it's program counter so it continues from the line after it's called but why is this code printing hello world twice when it's before the fork ``` #include <stdio.h> #include <sys/wait.h> int main() { printf("Hello World"); fork(); wait(NULL); return 0; } ```
printfdoesn't actually print -- it actually just puts data into a buffer to be printed later. It will actually be printed when the buffer gets flushed, which can happen in a variety of ways. In your case, the buffer flush doesn't happen until after the fork, so both the parent and the child have a copy of the string to be printed in the buffer when they fork, and both end up printing it.
I'm trying to figure out the correct way to pass database connection parameters to this libpq connection control function. PQconnectdbParams ``` PGconn *PQconnectdbParams(const char * const *keywords, const char * const *values, int expand_dbname); ```
Fromthe documentation: This function opens a new database connection using the parameters taken from two NULL-terminated arrays. The first, keywords, is defined as an array of strings, each one being a key word. The second, values, gives the value for each key word. I have never used this function in practice (asPQconnectdb()seems simpler), but this example should work I think: ``` char *keywords[] = {"hostaddr", "port", "dbname", 0}; char *values[] = {"127.0.0.1", "5432", "testdb", 0}; conn = PQconnectdbParams((const char **)keywords, (const char **)values, 0); ```
I have a structure defined as ``` struct Bod{ int x, y; }; ``` Then I have a function ``` void add(struct Bod* s) { h[++nh] = s; } ``` And in next function, I tried to pass array into the previous function, which gives me errorIncompatible type for argument 1 of function add() ``` void bfs(struct Bod* body, int start_index){ struct Bod* v; add(body[start_index]); ... } ``` And in main, I have created this array of struct like this ``` struct Bod body[m*n]; ``` What did I miss?
Sincebody[start_index]gives youoneelement ofbodyat indexstart_index, you end up passing in that single element toadd(). If you want to pass in the array itself, you just need to pass inbodyas-is: ``` add(body); ``` Or, to pass in the array starting at a given index: ``` add(&body[start_index]); ```
``` #include <stdio.h> void main(){ FILE *fp[1024]; char FILENAME[1024]; int i; for(i=0;i<1024;i++){ sprintf(FILENAME,"file%d.txt",i); fp[i]=fopen(FILENAME,"w"); if(fp[i]==NULL){ printf("file %d cannot be opened\n",i); exit(0); } } } ``` In the above program I tried to create 1024 files but actually I could only create 508 files — running on Windows. Please help in resolving the issue.
You need to close each file after you create it. You are likely running into the limit on the maximum number of files you can have open per process (I am guessing that for you it will be 512). On linux/unix/BSD you can find out what the limit is with 'ulimit -l' More info here:https://unix.stackexchange.com/questions/36841/why-is-number-of-open-files-limited-in-linux
My code on codefights works well for all the test cases but doesn't pass one hidden test case. The problem is to convert the given year from 1<=year<=2005 into century. I wrote all the code. I just don't get what I should change to get the hidden test passed. This is my code: ``` int centuryFromYear(int year) { while(year>=1&&year<=2005) { int x=year/100; if(year%10==0) { return(x); } else { return(x+1); } } } ```
Corrected Code - ``` int centuryFromYear(int year) { int x=year/100; if(year%100==0) { return(x); } else { return(x+1); } } ``` You were almost there too. Hope this helps.
I can declare a function taking a function pointer as argument, ``` int bar(int (* a)()) { } // this works ``` I can apply the const qualifier to this argument, ``` int bar(int (* const a)()) { } // this works ``` But when I apply the restrict qualifier to this argument, I get an error ``` int bar(int (* restrict a)()) { } test.c:10:1: error: invalid use of ‘restrict’ int bar(int (* restrict a)()) ``` I am using cc ``` 0 % gcc --version gcc (GCC) 7.3.0 ```
Only pointers to objects may berestrictqualified: §6.7.3 Type qualifiersTypes other than pointer types whose referenced type is an object type shall not be restrict-qualified. A function is not an object: §3.15.1 objectregion of data storage in the execution environment, the contents of which can represent values
I just know how to add system calls to kernel of Linux. My system call (like lots of other system calls) takes a pointer to a struct created by me. If I want to add the struct to kernel source how and where should I add it?
Place a header containing the newstructininclude/uapi/linux. Avoid namespace pollution by using the appropriate types e.g.__u16instead ofunsigned short/uint16_t,__kernel_time_tinstead oftime_t...etc. Check outstruct mii_ioctl_datafor an example. By adding aheader-y += new_header.hentry toinclude/uapi/linux/Kbuild, you can then export the header withmake headers_install. By default, it installs the headers in./usr. If you want it to install them as system headers, usemake headers_install INSTALL_HDR_PATH=/usrinstead. This results in the contents of theuapidirectory being merged into/usr/include. You may then#include <linux/new_header.h>in your userspace program.
Objective To generate the hash of a image file. I am usingpHashlibrary for this task. pHash library has below method used for generating the image hash. ``` int ph_dct_imagehash(const char* file,ulong64 &hash); ``` Datatype ulong64 is not present in android stdint.h. Due to which I am getting"cannot resolve type ulong64"error. Please help how I can use ulong64 in c file in Android. Can I use some third party library for this task? Do we have any way around to fix this error?
This type is specific to pHash, and it is defined inside pHash.h by the following snippet: ``` #if defined( _MSC_VER) || defined(_BORLANDC_) typedef unsigned _uint64 ulong64; typedef signed _int64 long64; #else typedef unsigned long long ulong64; typedef signed long long long64; #endif ``` To use this type, just#include <pHash.h>.
How to delete all the nodes in singly circular linked list? Is this code the right one ? I don't get the output in codeblocks when I tried for it. What is the mistake? ``` void deleteall() { struct node *temp1=head,*temp2; do { while(temp1->next!=head) { temp1=temp1->next; } temp2=head; head=head->next; temp1->next=head; free(temp2); }while(temp1!=head); head=NULL; free(temp1); printf("deleted successfully\n"); } ```
To delete a singly circular linked list, start from thenextofheadand keep on deleting until you reach toheadand then deleteheadof the list, like this: ``` struct node *temp1 = head->next, *temp2; while (temp1 != head) { temp2 = temp1->next; free(temp1); temp1 = temp2; } free (head); head = NULL; ```
I'm using the function__builtin_clzprovided by GCC, which should count the number of leading zero bits in anunsigned int. But__builtin_clzreturns an incorrect value for input0: ``` #include <stdio.h> int main(void) { unsigned int x = 0; int lz = __builtin_clz(x); printf("%d\n", lz); return 1; } ``` I expect this to print32on my machine. Instead, it prints4195634: ``` $ gcc -Wall clz.c $ ./a.out 4195634 ``` Is this my fault? Have I invoked some undefined behavior somewhere?
Is this my fault? Have I invoked some undefined behavior somewhere? Yes, by passing 0 to__builtin_clz. From theGCC documentation: Returns the number of leading 0-bits in x, starting at the most significant bit position.If x is 0, the result is undefined.
I am trying to use a simpleDHCP clientfrom GitHub. When I try to run this client it fails with ``` eth0 MAC : C8:6B:00:E5:52:5E Couldn't open device eth0: eth0: socket: Invalid argument ``` Any advices? Thanks!
Clearlypcap_open_live()returns withNULL. pcap_open_live()returns apcap_t *on success andNULLon failure. IfNULLis returned,errbufis filled in with an appropriate error message.errbufmay also be set to warning text whenpcap_open_live()succeds; to detect this case the caller should store a zero-length string inerrbufbefore callingpcap_open_live()and display the warning to the user iferrbufis no longer a zero-length string.errbufis assumed to be able to hold at leastPCAP_ERRBUF_SIZEchars. You may want to investigate your card. Check as root: ``` su -c "lspci | grep -i ether" ``` Check that this device is in facteth0 ``` /usr/sbin/ethtool -i eth0 ``` and ``` dmesg | grep eth0 ```
I just know how to add system calls to kernel of Linux. My system call (like lots of other system calls) takes a pointer to a struct created by me. If I want to add the struct to kernel source how and where should I add it?
Place a header containing the newstructininclude/uapi/linux. Avoid namespace pollution by using the appropriate types e.g.__u16instead ofunsigned short/uint16_t,__kernel_time_tinstead oftime_t...etc. Check outstruct mii_ioctl_datafor an example. By adding aheader-y += new_header.hentry toinclude/uapi/linux/Kbuild, you can then export the header withmake headers_install. By default, it installs the headers in./usr. If you want it to install them as system headers, usemake headers_install INSTALL_HDR_PATH=/usrinstead. This results in the contents of theuapidirectory being merged into/usr/include. You may then#include <linux/new_header.h>in your userspace program.
Objective To generate the hash of a image file. I am usingpHashlibrary for this task. pHash library has below method used for generating the image hash. ``` int ph_dct_imagehash(const char* file,ulong64 &hash); ``` Datatype ulong64 is not present in android stdint.h. Due to which I am getting"cannot resolve type ulong64"error. Please help how I can use ulong64 in c file in Android. Can I use some third party library for this task? Do we have any way around to fix this error?
This type is specific to pHash, and it is defined inside pHash.h by the following snippet: ``` #if defined( _MSC_VER) || defined(_BORLANDC_) typedef unsigned _uint64 ulong64; typedef signed _int64 long64; #else typedef unsigned long long ulong64; typedef signed long long long64; #endif ``` To use this type, just#include <pHash.h>.
How to delete all the nodes in singly circular linked list? Is this code the right one ? I don't get the output in codeblocks when I tried for it. What is the mistake? ``` void deleteall() { struct node *temp1=head,*temp2; do { while(temp1->next!=head) { temp1=temp1->next; } temp2=head; head=head->next; temp1->next=head; free(temp2); }while(temp1!=head); head=NULL; free(temp1); printf("deleted successfully\n"); } ```
To delete a singly circular linked list, start from thenextofheadand keep on deleting until you reach toheadand then deleteheadof the list, like this: ``` struct node *temp1 = head->next, *temp2; while (temp1 != head) { temp2 = temp1->next; free(temp1); temp1 = temp2; } free (head); head = NULL; ```
I'm using the function__builtin_clzprovided by GCC, which should count the number of leading zero bits in anunsigned int. But__builtin_clzreturns an incorrect value for input0: ``` #include <stdio.h> int main(void) { unsigned int x = 0; int lz = __builtin_clz(x); printf("%d\n", lz); return 1; } ``` I expect this to print32on my machine. Instead, it prints4195634: ``` $ gcc -Wall clz.c $ ./a.out 4195634 ``` Is this my fault? Have I invoked some undefined behavior somewhere?
Is this my fault? Have I invoked some undefined behavior somewhere? Yes, by passing 0 to__builtin_clz. From theGCC documentation: Returns the number of leading 0-bits in x, starting at the most significant bit position.If x is 0, the result is undefined.
I am trying to use a simpleDHCP clientfrom GitHub. When I try to run this client it fails with ``` eth0 MAC : C8:6B:00:E5:52:5E Couldn't open device eth0: eth0: socket: Invalid argument ``` Any advices? Thanks!
Clearlypcap_open_live()returns withNULL. pcap_open_live()returns apcap_t *on success andNULLon failure. IfNULLis returned,errbufis filled in with an appropriate error message.errbufmay also be set to warning text whenpcap_open_live()succeds; to detect this case the caller should store a zero-length string inerrbufbefore callingpcap_open_live()and display the warning to the user iferrbufis no longer a zero-length string.errbufis assumed to be able to hold at leastPCAP_ERRBUF_SIZEchars. You may want to investigate your card. Check as root: ``` su -c "lspci | grep -i ether" ``` Check that this device is in facteth0 ``` /usr/sbin/ethtool -i eth0 ``` and ``` dmesg | grep eth0 ```
How to delete all the nodes in singly circular linked list? Is this code the right one ? I don't get the output in codeblocks when I tried for it. What is the mistake? ``` void deleteall() { struct node *temp1=head,*temp2; do { while(temp1->next!=head) { temp1=temp1->next; } temp2=head; head=head->next; temp1->next=head; free(temp2); }while(temp1!=head); head=NULL; free(temp1); printf("deleted successfully\n"); } ```
To delete a singly circular linked list, start from thenextofheadand keep on deleting until you reach toheadand then deleteheadof the list, like this: ``` struct node *temp1 = head->next, *temp2; while (temp1 != head) { temp2 = temp1->next; free(temp1); temp1 = temp2; } free (head); head = NULL; ```
I'm using the function__builtin_clzprovided by GCC, which should count the number of leading zero bits in anunsigned int. But__builtin_clzreturns an incorrect value for input0: ``` #include <stdio.h> int main(void) { unsigned int x = 0; int lz = __builtin_clz(x); printf("%d\n", lz); return 1; } ``` I expect this to print32on my machine. Instead, it prints4195634: ``` $ gcc -Wall clz.c $ ./a.out 4195634 ``` Is this my fault? Have I invoked some undefined behavior somewhere?
Is this my fault? Have I invoked some undefined behavior somewhere? Yes, by passing 0 to__builtin_clz. From theGCC documentation: Returns the number of leading 0-bits in x, starting at the most significant bit position.If x is 0, the result is undefined.
I am trying to use a simpleDHCP clientfrom GitHub. When I try to run this client it fails with ``` eth0 MAC : C8:6B:00:E5:52:5E Couldn't open device eth0: eth0: socket: Invalid argument ``` Any advices? Thanks!
Clearlypcap_open_live()returns withNULL. pcap_open_live()returns apcap_t *on success andNULLon failure. IfNULLis returned,errbufis filled in with an appropriate error message.errbufmay also be set to warning text whenpcap_open_live()succeds; to detect this case the caller should store a zero-length string inerrbufbefore callingpcap_open_live()and display the warning to the user iferrbufis no longer a zero-length string.errbufis assumed to be able to hold at leastPCAP_ERRBUF_SIZEchars. You may want to investigate your card. Check as root: ``` su -c "lspci | grep -i ether" ``` Check that this device is in facteth0 ``` /usr/sbin/ethtool -i eth0 ``` and ``` dmesg | grep eth0 ```
PVS-Studio gave me a warning about this : ``` char c; sscanf(line, "%d", &c); ``` I changed %d to %c but this created a bug because "c" now contains the ASCII value of the number and not the decimal one, so I went back to "%d". So what's the correct specifier to ? is there another solution ?
cis achar. You asked to scan anint. PVS-Studio did right in warning you. Change the type ofctointand scan for a%d.
I am just started C programming and installed minGW. While doing my Hello world test program, I am getting an error as below while compiling my 'test.c' hello world file using - g++ test.c. test.c:1:5: error:'i' does not name a type y_# i n c l u d e My code - ``` #include <stdio.h> int main () { printf ("Hello, World!/n") return 0; } ``` my path is C:\minGW. I also find stdio.h as installed file - /include/ssp/stdio.h Can any one tell me what I am missing here.This could help me to start my journey.
The messagey_# i n c l u d eand the double line end suggest that the filetest.cis encoded in UTF-16 encoding. Change the file encoding to ascii, it will solve your problem.
In my program I need to detect if the spacebar is pressed 3 times and then replace it whit a \n. I am using getchar for getting my input and detecting one space is no problem but if I enter 3 spaces to check it does not work. Any help is very appreciated This is my code so far witch works perfectly fine if I only check one spacebar but if I enter 3 of the it will not detect it ``` if (c == ' ') { putchar('\n'); } ```
You can count the number of consecutive spaces. Something like: ``` int c; int spaces = 0; while((c = getchar()) != EOF) { if (c == ' ') { ++spaces; if (spaces == 3) { putchar('\n'); spaces = 0; } } else { spaces = 0; } } ```
Is it wrong at all and there is no way, or i have to do it somewhat else? For example: ``` typedef void (*UserFunc)(Test *tx); typedef struct{ int a; char b; UserFunc func; } Test; ``` i get this error: ``` c.c:5:26: error: unknown type name ‘Test’ typedef void (*UserFunc)(Test *tx); ^~~~ c.c:10:1: error: unknown type name ‘UserFunc’ UserFunc func; ^~~~~~~~ ``` When i move down function typedef: ``` typedef struct{ int a; char b; UserFunc func; } Test; typedef void (*UserFunc)(Test *tx); ``` I get: ``` c.c:8:1: error: unknown type name ‘UserFunc’ UserFunc func; ^~~~~~~~ ```
You have to declare Test first, and define it later : ``` typedef struct Test Test; typedef void (*UserFunc)(Test *tx); typedef struct Test { int a; char b; UserFunc func; } Test; ```
Hello i just need to see why my Gcc stopped working after execution. ``` #include<stdio.h> int main() { static char *s[] = {"black", "white", "pink", "violet"}; char **ptr[] = {s+3, s+2, s+1, s}, ***p; p=ptr; ++p; printf("the value of **p is %s\n\t",**p); // printed on screen pink printf("the value of **ptr[1] is %s\n\t",**ptr[1]); // here got the error printf("the value of *(s[2]) is %s\n\t",*s[2]); // here got the error return 0; } ```
**ptr[1]is achar. You are passing it toprintffor a%sconversion.%srequires a pointer tochar, not achar. Pass*ptr[1]instead. Similarly, instead of*s[2], passs[2].
I'm trying to write a method in C that accepts three integers: start, end, and mask. If mask is 1, all bits except the bits in the range of start to end are set to 0, and the bits in the range are set to 1. I have this part working at the moment: ``` for (int i = 0; i < (end - start + 1); i++) { if (mask == 1) { ret |= ret << 1; ret |= ret | 1; } }...ret = ret << start; ``` (where 'ret' is an unsigned int and simply starts as 0 if mask is 1 or ~0 if mask is 0). However, I cannot seem to figure out how to do it the other way: masking a range of bits as 0 and setting all of the rest to 1.
Since flipping the mask from 1 to 0 simply inverts the result, you can ignore the mask, build the return formask == 1, and flip its bits at the end if the mask is zero: ``` int ret = 0; for (int i = start ; i <= end ; i++) { ret |= 1 << i; } if (!mask) { ret = ~ret; } ```
I had to test if my machine is using the little or the big endian. For this reason i wrote this code. I can see that my machine is using the little endian. But i dont know why the output from my first byte is only D. Should it not be 0D? ``` union int2byte { unsigned char bytes[4]; unsigned int hex; }; int main(int argc, const char* argv[]) { union int2byte hexby; hexby.hex = 0xBAADF00D; printf("%u\n",hexby.hex); int counter; for(counter = 0; counter < 4; counter = counter + 1) { printf("Hex for Byte %u is %X.\n",counter+1, hexby.bytes[counter]); } } Output: 3131961357 Hex for Byte 1 is D. Hex for Byte 2 is F0. Hex for Byte 3 is AD. Hex for Byte 4 is BA. ```
%Xdoes not output leading zeros. Use%02Xinstead. The2tells it to output at least 2 digits, and the0tells it to pad the output on the left side with a'0'character if the output is less than 2 digits.
while going through the first chapter I found a question *to remove all comments from a code" - I really don't know what the author expects, whether I am supposed to use File handling (which in later chapters) or am I supposed to type in the entire file as an input?
You don't need file handling, you can use "getline" like in the later examples in chapter 1 to parse lines. Then if you want to use your code on a file you can pipe the file as input to the executable you have written. You could also use "getchar" as in the "wc" example (line, word, and character counting example) given in Section 1.5.4. In that example program there is no file handling, but you can pipe a file the executable just as you would for the usual linux "wc" utility.
I recently learned thatsizeofis not a function and actually evaluates at compile time. But I still haven't been able to figure out howsizeof(*NULL)is equal to 1. EDIT: I'm talking about gcc here specifically.
It depends on the compiler and standard library. With GCC and glibc,NULLis defined as(void*)0and GCC hasan extensionthat allows pointer arithmetic onvoidpointers usingsizeof(void) == 1. Without this extension, the compiler would produce an error. A standard library could also defineNULLas0. In this casesizeof(*NULL)would also be illegal.
I have a nested struct, which I am attempting to fill with user data. The struct: ``` typedef struct gameInfo { char title[MAX]; char platform[MAX]; char developer[MAX]; unsigned int year; struct borrowerInfo { bool borrowed; char nameOfBorrower[MAX]; char date[MAX]; } borrower; } game; ``` I am usinggets()andscanf()to get the data from the user: ``` gets(game.title); gets(game.platform); gets(game.developer); scanf("%d",&game.year); ``` However, I get the error: ``` error: expected expression before 'game' gets(game.title); ^~~~ ``` What am I doing wrong?
gameis the name of a type, not a variable. You need to declare a variable of that type: ``` game mygame; ``` Then populatemygame. Also, never usergets, as the function can overrun the buffer it's writing to. Better to usefgetsinstead.
I would like to allocate a buffer within 32-bit address space on 64-bit ARM. In other words, I would like to ensure that my buffer is bound to the lower 32-bit address space. Do you know a nice C function which does that?
There is no C standard function to do so. However, since you tagged the question as Linux, take a look atmmap(2)and theMAP_ANONYMOUSandMAP_32BITflags, e.g.: ``` mmap( 0, 1, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_32BIT, -1, 0 ); ``` Another option is passing an explicit address in the lower 32-bit address space using theMAP_FIXEDflag: ``` mmap( (void *)0x10000, 1, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0 ); ```
In the terminal for my autocomplete implementation, the commands are displaying after pressing theENTER.But I want to change the terminal behavior such that the commands will be displayed without pressing enter. My question is how to change the terminal settings for displaying the commands when I pressTABwithout pressingENTER?
You need to use an OS-specific way to control the terminal, like theConsole API for Windows. There are also cross-platform libraries that you can use as well, like thencurses library. Read also aboutTerminal capabilitiesfor more information.
I had to test if my machine is using the little or the big endian. For this reason i wrote this code. I can see that my machine is using the little endian. But i dont know why the output from my first byte is only D. Should it not be 0D? ``` union int2byte { unsigned char bytes[4]; unsigned int hex; }; int main(int argc, const char* argv[]) { union int2byte hexby; hexby.hex = 0xBAADF00D; printf("%u\n",hexby.hex); int counter; for(counter = 0; counter < 4; counter = counter + 1) { printf("Hex for Byte %u is %X.\n",counter+1, hexby.bytes[counter]); } } Output: 3131961357 Hex for Byte 1 is D. Hex for Byte 2 is F0. Hex for Byte 3 is AD. Hex for Byte 4 is BA. ```
%Xdoes not output leading zeros. Use%02Xinstead. The2tells it to output at least 2 digits, and the0tells it to pad the output on the left side with a'0'character if the output is less than 2 digits.
while going through the first chapter I found a question *to remove all comments from a code" - I really don't know what the author expects, whether I am supposed to use File handling (which in later chapters) or am I supposed to type in the entire file as an input?
You don't need file handling, you can use "getline" like in the later examples in chapter 1 to parse lines. Then if you want to use your code on a file you can pipe the file as input to the executable you have written. You could also use "getchar" as in the "wc" example (line, word, and character counting example) given in Section 1.5.4. In that example program there is no file handling, but you can pipe a file the executable just as you would for the usual linux "wc" utility.
I recently learned thatsizeofis not a function and actually evaluates at compile time. But I still haven't been able to figure out howsizeof(*NULL)is equal to 1. EDIT: I'm talking about gcc here specifically.
It depends on the compiler and standard library. With GCC and glibc,NULLis defined as(void*)0and GCC hasan extensionthat allows pointer arithmetic onvoidpointers usingsizeof(void) == 1. Without this extension, the compiler would produce an error. A standard library could also defineNULLas0. In this casesizeof(*NULL)would also be illegal.
I have a nested struct, which I am attempting to fill with user data. The struct: ``` typedef struct gameInfo { char title[MAX]; char platform[MAX]; char developer[MAX]; unsigned int year; struct borrowerInfo { bool borrowed; char nameOfBorrower[MAX]; char date[MAX]; } borrower; } game; ``` I am usinggets()andscanf()to get the data from the user: ``` gets(game.title); gets(game.platform); gets(game.developer); scanf("%d",&game.year); ``` However, I get the error: ``` error: expected expression before 'game' gets(game.title); ^~~~ ``` What am I doing wrong?
gameis the name of a type, not a variable. You need to declare a variable of that type: ``` game mygame; ``` Then populatemygame. Also, never usergets, as the function can overrun the buffer it's writing to. Better to usefgetsinstead.
I would like to allocate a buffer within 32-bit address space on 64-bit ARM. In other words, I would like to ensure that my buffer is bound to the lower 32-bit address space. Do you know a nice C function which does that?
There is no C standard function to do so. However, since you tagged the question as Linux, take a look atmmap(2)and theMAP_ANONYMOUSandMAP_32BITflags, e.g.: ``` mmap( 0, 1, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_32BIT, -1, 0 ); ``` Another option is passing an explicit address in the lower 32-bit address space using theMAP_FIXEDflag: ``` mmap( (void *)0x10000, 1, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0 ); ```
In the terminal for my autocomplete implementation, the commands are displaying after pressing theENTER.But I want to change the terminal behavior such that the commands will be displayed without pressing enter. My question is how to change the terminal settings for displaying the commands when I pressTABwithout pressingENTER?
You need to use an OS-specific way to control the terminal, like theConsole API for Windows. There are also cross-platform libraries that you can use as well, like thencurses library. Read also aboutTerminal capabilitiesfor more information.
I would like to replace the'character with\'I use the following code: ``` #include <stdio.h> #include <string.h> int main() { int i, j = 0; char str[] = "HELLO'All"; char pch[128] = { 0 }; for (i = 0; i < strlen(str); i++) { if (str[i] == '\'') { pch[j] = '\\'; printf(" pch[%d] = *%c* \n", j, pch[j]); pch[++j] = str[i]; continue; } pch[j++] = str[i]; } printf("pch = *%s* \n", pch); return 0; } ``` I get the result:pch = *HELLO\All*Expected result:pch = *HELLO\'All*What is missing in my code?
It seems you miss an increment ofj Try like this ``` pch[j++]='\\'; printf(" pch[%d] = *%c* \n",j-1, pch[j-1]); pch[j++]=str[i]; ``` or like this ``` pch[j]='\\'; printf(" pch[%d] = *%c* \n",j, pch[j]); ++j; pch[j++]=str[i]; ```
I have encountered a terse piece of code which I am finding very difficult to decipher. ``` for (int k = 0; k < count; k++) { C[p=w[T[k]]++] = Y1[k]; CC[p] = Y2[k] } ``` w and T look like this: ``` w = [0 3 6 8] T = [2 0 3 2 1 0 1 3 0 1] ``` I am unable to figure what is the index that the arrayCandCCare going to get when k = 0 and a way to read the code easily. This is what I had tried to do. When ``` k = 0, T[0] = 2, w[2] = 6 p = 6 w[2] = 7 c[6] and cc[6] are assigned ```
Rewrite it. This code is equivalent to: ``` for (int k = 0; k < count; k++) { p = w[T[k]]++; C[p] = Y1[k]; CC[p] = Y2[k] } ``` which is the same as ``` for (int k = 0; k < count; k++) { p = w[T[k]]; // For k=0 => w[2]=6 => p=6 w[T[k]]++; // For k=0 => increment w[2], so w[2] is 7 C[p] = Y1[k]; // C[6] = Y1[0] CC[p] = Y2[k] // CC[6] = Y2[0] } ```
I recently noticed that ``` void foo(int array[10]); ``` Does not load the stack with the content of array whenfoois called, so the declaration is equivalent to: ``` void foo(int *array): ``` I would like to find the section in the C99 standard that assert this behavior, but I don't find anything or I don't know what I should search for. So far I triedby reference,by value,function call,passing arguments, ...
C11 6.7.6.3 §7. (C99 6.7.5.3 §7) A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation. The term is formally named "array adjustment". Informally outside the C standard, it is usually referred to as "array decay".
I have written a simple command-line based audio player in C using libVLC library. Every time a audio file is played, an album art (.jpg format) and a directory in the track's name will be created for each track, inside '~/.cache/vlc' folder which is taking up significant disk space and creating lots of directories. I have thousands of tracks and this is becoming a concern. Need help on disabling this.
The easiest way I found around this knotty little issue was to create the directory$HOME/.cache/vlc/artand simply make itread only.If vlc can't write to it:a. The issue disappearsb. vlc doesn't complain about it.
ing_hash_table_new(HashFunc hash_func, GEqualFunc key_equal_func) HashFunc they have this types: g_direct_hash()g_int_hash()g_int64_hash()g_double_hash()g_str_hash() GEqualFunc they have this types: g_direct_equal()g_int_equal()g_int64_equal()g_double_equal()g_str_equal() Which type can i use to have a key that is a long and a value that is a pointer for a struct that i have defined?
Summarizing from comments: Assuming you build for a system where a pointer is at least as many bits as a long (true on most systems), yes, you can cast it to agconstpointerand useg_direct_*. You do build in a dependency on that fact into your code that way though. Otherwise: do not uselongbut eithergintorgint64for your values and pass pointers to them tog_int_*org_int64_*. Usinglong, which can differ in actual size per system, in portable code is not handy anyway. g_direct_*use the pointers themselves instead of the values pointed to by them.
I am facing difficulty in converting a binary array to a decimal number: ``` bin[8] = {10,00,00,10}; ``` I want the equivalent of this array element as a decimal number, i.e.130.
A standard solution goes like this: ``` int f(char s[]) { int n = 0; int i; for (i = 0; i < 8; ++i) { n <<= 1; n += s[i] - '0'; } return n; } ```
I am trying to dynamically show a specific number of decimals. I use this : ``` char graduationText[1024]; sprintf("%.*f", graduationText, decimalsToShow, graduation); ``` However when the program run I get a memory violation error. So I was wondering if sprintf can manage the "%.*f" or if it an error of me. Thanks
Thedocumentation forsprintfreads like: int sprintf(char *str, const char *format, ...);sprintf()[et al.] ... write to the character stringstr. You suffered undefined behavior due tosprintfattempting to read uninitialized memory to use as the format string, and attempting to write to a string literal. However, you should prefersnprintftosprintfto help you avoid buffer overflow issues. ``` int r = snprintf(graduationText, 1024, "%.*f", decimalsToShow, graduation); ```
I have encountered a terse piece of code which I am finding very difficult to decipher. ``` for (int k = 0; k < count; k++) { C[p=w[T[k]]++] = Y1[k]; CC[p] = Y2[k] } ``` w and T look like this: ``` w = [0 3 6 8] T = [2 0 3 2 1 0 1 3 0 1] ``` I am unable to figure what is the index that the arrayCandCCare going to get when k = 0 and a way to read the code easily. This is what I had tried to do. When ``` k = 0, T[0] = 2, w[2] = 6 p = 6 w[2] = 7 c[6] and cc[6] are assigned ```
Rewrite it. This code is equivalent to: ``` for (int k = 0; k < count; k++) { p = w[T[k]]++; C[p] = Y1[k]; CC[p] = Y2[k] } ``` which is the same as ``` for (int k = 0; k < count; k++) { p = w[T[k]]; // For k=0 => w[2]=6 => p=6 w[T[k]]++; // For k=0 => increment w[2], so w[2] is 7 C[p] = Y1[k]; // C[6] = Y1[0] CC[p] = Y2[k] // CC[6] = Y2[0] } ```
I recently noticed that ``` void foo(int array[10]); ``` Does not load the stack with the content of array whenfoois called, so the declaration is equivalent to: ``` void foo(int *array): ``` I would like to find the section in the C99 standard that assert this behavior, but I don't find anything or I don't know what I should search for. So far I triedby reference,by value,function call,passing arguments, ...
C11 6.7.6.3 §7. (C99 6.7.5.3 §7) A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation. The term is formally named "array adjustment". Informally outside the C standard, it is usually referred to as "array decay".
I have written a simple command-line based audio player in C using libVLC library. Every time a audio file is played, an album art (.jpg format) and a directory in the track's name will be created for each track, inside '~/.cache/vlc' folder which is taking up significant disk space and creating lots of directories. I have thousands of tracks and this is becoming a concern. Need help on disabling this.
The easiest way I found around this knotty little issue was to create the directory$HOME/.cache/vlc/artand simply make itread only.If vlc can't write to it:a. The issue disappearsb. vlc doesn't complain about it.
ing_hash_table_new(HashFunc hash_func, GEqualFunc key_equal_func) HashFunc they have this types: g_direct_hash()g_int_hash()g_int64_hash()g_double_hash()g_str_hash() GEqualFunc they have this types: g_direct_equal()g_int_equal()g_int64_equal()g_double_equal()g_str_equal() Which type can i use to have a key that is a long and a value that is a pointer for a struct that i have defined?
Summarizing from comments: Assuming you build for a system where a pointer is at least as many bits as a long (true on most systems), yes, you can cast it to agconstpointerand useg_direct_*. You do build in a dependency on that fact into your code that way though. Otherwise: do not uselongbut eithergintorgint64for your values and pass pointers to them tog_int_*org_int64_*. Usinglong, which can differ in actual size per system, in portable code is not handy anyway. g_direct_*use the pointers themselves instead of the values pointed to by them.
I am facing difficulty in converting a binary array to a decimal number: ``` bin[8] = {10,00,00,10}; ``` I want the equivalent of this array element as a decimal number, i.e.130.
A standard solution goes like this: ``` int f(char s[]) { int n = 0; int i; for (i = 0; i < 8; ++i) { n <<= 1; n += s[i] - '0'; } return n; } ```
I'm exploring regex, but I simply could not achieve exactly what I want yet. I'm using NetBeans and I need to swap allstrncpy(... , sizeof(x))tostrncpy(... , sizeof(x) -1 ), i.e, add the"-1"between the last parenthesis. An example should be: ``` strncpy(data->error, t_result[ID(data->modulo)].status, sizeof(data->error)); //need below strncpy(data->error, t_result[ID(data->modulo)].status, sizeof(data->error) - 1); ```
See regex in use here ``` (strncpy\(.*?sizeof\([^)]*\)) ``` (strncpy\(.*?sizeof\([^)]*\))Capture the following into capture group 1strncpy\(Matchesstrncpy(literally.*?Matches any character any number of times, but as few as possiblesizeof\(Matchessizeof(literally[^)]*Matches any character except)any number of times\)Matches)literally Replacement$1 - 1 Result in: ``` strncpy(data->error, t_result[ID(data->modulo)].status, sizeof(data->error) - 1); ```
I have .so file which I take from apk. With command nm -D libnative-lib.so I took list of functions. I need to call function namedJava_com_example_nativelib_utils_Constants_getStringFromJNI. I wrote the code below: ``` #include <stddef.h> #include <dlfcn.h> #include <stdio.h> int init_library() { void* hdl = dlopen("./libnative-lib.so", RTLD_LAZY); if(hdl == 0) return 0; else return 1; } int main() { printf("%s\n", (init_library() ? "OK": "ERROR")); } ``` and make file: ``` all: exe exe: main.c gcc main.c -fPIC -ldl -o main ``` but result of program is always "ERROR". I tried libnative-lib.so from x86 and armeabi-v7a architectures (others not present). How to load library and call function from it? C++ or C do not care.
It is not possible to use android .so files in non-android project. similar question ishere
I have the following code (simplified for here). ``` #include <stdio.h> #include <stdlib.h> struct inner { int a; int b; }; struct outer { struct inner *next; struct inner *prev; }; int main(int argc, char *argv[]) { struct outer *c = malloc(sizeof(struct outer)); if (c->next) { printf("here\n"); } if (c->next != NULL) { printf("here too"); } } ``` As you can see above,conly has memory allocated, soc->nextandc->prevare NULL addresses. But both print statements still run. How do I get theifstatement to work only ifc->nextis not a null pointer?
A.malloc()does not initialize memory to zero, so your pointers are not necessarilyNULL B. accessing an uninitialized pointer results in undefined behavior C.c->nextandc->next != NULLare basically the same condition check
Suppose I have the variable declarationchar **p. Does that mean thatpis a pointer to acharpointer or thatpis a pointer to a pointer of some type that points to achar? There is a subtle difference between these two chains of pointers. In other words, what I am trying to ask is given acharpointer to a pointerchar **p,*pcan obviously be a pointer to achar *, but could it also point to some other pointer type likevoid *which in turn points to achar?
The type of*pis alwayschar *. It cannot be avoid*that happens to be pointing to achar.
Why does the first printf() output 1 and the second one 8589934593? EDIT: Why does the second one output exactly 8589934593 and not some other number? ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]){ int *intPtr = NULL; long *longPtr = NULL; int array[5] = {0,1,2,3,4}; intPtr = &array[1]; longPtr = &array[1]; printf("%d\n", *intPtr); printf("%ld\n", *longPtr); } ```
Because it's undefined behavior. Pointing along*to the address of anintand acting like it's alongviolates the strict aliasing rule, giving you undefined behavior.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed5 years ago.Improve this question How to store a symmetric key safely? Can I use pkcs12 to store this symmetric key?
Simple Answer: It is impossible. As soon as "you" store the key, it is unsafe as your program is just a usual program running on a computer. Some better ways (depending on your use-case) - use hardware tokens and their associated drivers / APIs - use the operating system's crypto APIs and credential stores - encrypt the keyfile with another layer of security, e.g., a password The second approach is the most widely used as far as all involved operating systems support this.
Being a Javascript programmer, I'm really not quite familiar with the compiling process. My problem is locating source files during compilation with Emscripten. My "include"-commands refer to source code, such as "Core/main.h", which in turn refers to other source files in the same folder, yet using a similar address, (e.g. "Core/app.h") How do I overcome these "File not found" errors? How do I indicate to the Emscripten compiler that it should look in the source folder? I've been reading the documentation, but what I'm finding discusses, I think, virtual file systems for use during run time, not included directories during compilation.
It's the one argument that is the same on virtually every C/C++ compiler: -I ``` emcc -Idir1 -Idir2 ... foo.c ``` Where the file is at dir1/Core/app.h.
I need to write a function which gets an array, it's size and a pointer, I need to check if the pointer exists in the array and if so, print all the elements after it and i'm not allowed to create local variables or use []. This is what i did to find whether the pointer exists or not. ``` void printAfterX(int* arr, int n, int* x) { if (x < (arr + n) && x >= arr) { } } ``` Thank you.
I'll give you two hints: (1) Function parameters are l-values. (2) Eventually recursion. You should try both, even if recusion is an overkill here.
I'm confused. Why in this programagives me0xFFFFFFA0butbgives me0xA0? It's weird. ``` #include <stdio.h> int main() { char a = 0xA0; int b = 0xA0; printf("a = %x\n", a); printf("b = %x\n", b); } ```
Default type ofaissignedinchar a = 0xA0;and in anysigned data typewhether itschar of intyou should be careful ofsign bit, ifsign bitissetmeans number will be negative and store astwo's complimentway. ``` char a = 0xA0; /* only 1 byte for a but since sign bit is set, it gets copied into remaining bytes also */ a => 1010 0000 | this sign bit gets copied 1111 1111 1111 1111 1111 1111 1010 0000 f f f f f f A 0 ``` In case ofint b = 0xA0;sign bit(31st bit)is0so what ever it contains i.e0xA0will be printed.
``` #include <stdio.h> int main() { int i[ ] = {3, 5}; int *p = i; int j = --*p++; printf("j = %d\n\n", j); return 0; } ``` Can someone explain to me why the answer is "j = 2"? This code from the course notebook; they didn't explain it in the book.
This behavior can be described asoperator precedenceand it's something to do with how C compiler processed your code. In this case, the postfixed++operator takes precedence over*operator and incremented the pointer-to-arrayafteryou decremented the value of the dereferenced pointer with prefixed--, safe to say it's similarly written as such: ``` int main() { int i[ ] = {3, 5}; int *p = i; int j = --(*p++); printf("j = %d\n\n", j); return 0; } ``` References: How to increment a pointer address and pointer's value?http://en.cppreference.com/w/c/language/operator_precedence
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed5 years ago.Improve this question How to store a symmetric key safely? Can I use pkcs12 to store this symmetric key?
Simple Answer: It is impossible. As soon as "you" store the key, it is unsafe as your program is just a usual program running on a computer. Some better ways (depending on your use-case) - use hardware tokens and their associated drivers / APIs - use the operating system's crypto APIs and credential stores - encrypt the keyfile with another layer of security, e.g., a password The second approach is the most widely used as far as all involved operating systems support this.
Being a Javascript programmer, I'm really not quite familiar with the compiling process. My problem is locating source files during compilation with Emscripten. My "include"-commands refer to source code, such as "Core/main.h", which in turn refers to other source files in the same folder, yet using a similar address, (e.g. "Core/app.h") How do I overcome these "File not found" errors? How do I indicate to the Emscripten compiler that it should look in the source folder? I've been reading the documentation, but what I'm finding discusses, I think, virtual file systems for use during run time, not included directories during compilation.
It's the one argument that is the same on virtually every C/C++ compiler: -I ``` emcc -Idir1 -Idir2 ... foo.c ``` Where the file is at dir1/Core/app.h.
I need to write a function which gets an array, it's size and a pointer, I need to check if the pointer exists in the array and if so, print all the elements after it and i'm not allowed to create local variables or use []. This is what i did to find whether the pointer exists or not. ``` void printAfterX(int* arr, int n, int* x) { if (x < (arr + n) && x >= arr) { } } ``` Thank you.
I'll give you two hints: (1) Function parameters are l-values. (2) Eventually recursion. You should try both, even if recusion is an overkill here.
I'm confused. Why in this programagives me0xFFFFFFA0butbgives me0xA0? It's weird. ``` #include <stdio.h> int main() { char a = 0xA0; int b = 0xA0; printf("a = %x\n", a); printf("b = %x\n", b); } ```
Default type ofaissignedinchar a = 0xA0;and in anysigned data typewhether itschar of intyou should be careful ofsign bit, ifsign bitissetmeans number will be negative and store astwo's complimentway. ``` char a = 0xA0; /* only 1 byte for a but since sign bit is set, it gets copied into remaining bytes also */ a => 1010 0000 | this sign bit gets copied 1111 1111 1111 1111 1111 1111 1010 0000 f f f f f f A 0 ``` In case ofint b = 0xA0;sign bit(31st bit)is0so what ever it contains i.e0xA0will be printed.
``` #include <stdio.h> int main() { int i[ ] = {3, 5}; int *p = i; int j = --*p++; printf("j = %d\n\n", j); return 0; } ``` Can someone explain to me why the answer is "j = 2"? This code from the course notebook; they didn't explain it in the book.
This behavior can be described asoperator precedenceand it's something to do with how C compiler processed your code. In this case, the postfixed++operator takes precedence over*operator and incremented the pointer-to-arrayafteryou decremented the value of the dereferenced pointer with prefixed--, safe to say it's similarly written as such: ``` int main() { int i[ ] = {3, 5}; int *p = i; int j = --(*p++); printf("j = %d\n\n", j); return 0; } ``` References: How to increment a pointer address and pointer's value?http://en.cppreference.com/w/c/language/operator_precedence
Being a Javascript programmer, I'm really not quite familiar with the compiling process. My problem is locating source files during compilation with Emscripten. My "include"-commands refer to source code, such as "Core/main.h", which in turn refers to other source files in the same folder, yet using a similar address, (e.g. "Core/app.h") How do I overcome these "File not found" errors? How do I indicate to the Emscripten compiler that it should look in the source folder? I've been reading the documentation, but what I'm finding discusses, I think, virtual file systems for use during run time, not included directories during compilation.
It's the one argument that is the same on virtually every C/C++ compiler: -I ``` emcc -Idir1 -Idir2 ... foo.c ``` Where the file is at dir1/Core/app.h.
I need to write a function which gets an array, it's size and a pointer, I need to check if the pointer exists in the array and if so, print all the elements after it and i'm not allowed to create local variables or use []. This is what i did to find whether the pointer exists or not. ``` void printAfterX(int* arr, int n, int* x) { if (x < (arr + n) && x >= arr) { } } ``` Thank you.
I'll give you two hints: (1) Function parameters are l-values. (2) Eventually recursion. You should try both, even if recusion is an overkill here.
I'm confused. Why in this programagives me0xFFFFFFA0butbgives me0xA0? It's weird. ``` #include <stdio.h> int main() { char a = 0xA0; int b = 0xA0; printf("a = %x\n", a); printf("b = %x\n", b); } ```
Default type ofaissignedinchar a = 0xA0;and in anysigned data typewhether itschar of intyou should be careful ofsign bit, ifsign bitissetmeans number will be negative and store astwo's complimentway. ``` char a = 0xA0; /* only 1 byte for a but since sign bit is set, it gets copied into remaining bytes also */ a => 1010 0000 | this sign bit gets copied 1111 1111 1111 1111 1111 1111 1010 0000 f f f f f f A 0 ``` In case ofint b = 0xA0;sign bit(31st bit)is0so what ever it contains i.e0xA0will be printed.
``` #include <stdio.h> int main() { int i[ ] = {3, 5}; int *p = i; int j = --*p++; printf("j = %d\n\n", j); return 0; } ``` Can someone explain to me why the answer is "j = 2"? This code from the course notebook; they didn't explain it in the book.
This behavior can be described asoperator precedenceand it's something to do with how C compiler processed your code. In this case, the postfixed++operator takes precedence over*operator and incremented the pointer-to-arrayafteryou decremented the value of the dereferenced pointer with prefixed--, safe to say it's similarly written as such: ``` int main() { int i[ ] = {3, 5}; int *p = i; int j = --(*p++); printf("j = %d\n\n", j); return 0; } ``` References: How to increment a pointer address and pointer's value?http://en.cppreference.com/w/c/language/operator_precedence
I want there to be no border at all. I tried the following code: ``` GtkCssProvider *provider = gtk_css_provider_new (); gtk_css_provider_load_from_data (GTK_CSS_PROVIDER (provider), "entry, .entry, GtkEntry { border-width:0px ; }", -1, NULL); GdkDisplay *display = gdk_display_get_default (); GdkScreen *screen = gdk_display_get_default_screen (display); gtk_style_context_add_provider_for_screen (screen, GTK_STYLE_PROVIDER (provider), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); ```
I fixed it withentry { border:none }
In this program (which basically copies the input into an array & finally display it) --> ``` #include<stdio.h> int main() { int c,i=0; char arr[100]; while((c=getchar())!=EOF) { if((((c>=65)&&(c<=90))||((c>=97)&&(c<=122)))||(c==' ')||(c=='\t')) arr[i]=c; i++; } printf("\n%s in print\n",arr); return 0; } ``` As to passEOFsuccessfully,CTRL+Dwas needed to be pressed twice or generally after hitting ENTER. So I wrote this version to allow only certain characters into the array. But the output is very dubious, sometimes it is giving error free output, other times it is not. Here is the output of two runs:
printf%stakes a string. You're passing itarr, which is not a string. A string needs a'\0'terminator to mark the end.
I wrote this C code to find the value for 3 squared. ``` #include <stdio.h> #include <math.h> int main( void ) { float a; a = powf( 3, 2 ); printf( "\n%f\n", a ); return 0; } ``` I get the warningimplicit declaration of function 'powf'even withmath.hlibrary included and-lmin the terminal command: ``` gcc -o test.exe -ansi -Wall test.c -lm ``` My gcc version is 4.2.2 if it helps.
powfis added in C99. Option-ansiis equivalent to-std=c89. You need to use-std=c99flag. ``` gcc -o test.exe -std=c99 -Wall test.c -lm ```
I know that it is possible to close an application by calling theexit(0)function. And that by using it, all heap-allocated memory prior to the call is cleared. So you do not have to worry about it. But to debug your program and investigate better if there is a memory leak, it is not practical to close the program without first releasing all memory. So I wanted to schedule the closure by adding the same message that the system sends by pressing the X button on a window (WM_CLOSE). With that message(or event), the program can execute the code that will close the application. So the question is if there is any function, or something from the winapi that adds that message to the current process?
You can use WINAPISendMessagewithWM_CLOSEfor theMsgparameter. Here more about this function:SendMessage
``` typedef int score; typedef struct tnode *ptrtonode; typedef ptrtonode tree; struct tnode{ score s; tree next; bool know; }; scanf("%d",&n); tree t[n]; for(i=0;i<n;i++){ scanf("%d",&x); t[i]->s=x; t[i]->next=NULL; t[i]->know=false; } ``` This is a code snippet. When it runs 't[i]->s=x;', this program will crash. I do not know why.
treeis of typestruct tnode *.tree t[n];declarestas an array ofnpointer tostruct tnode(struct tnode *). You need to allocate memory to these pointers before accessing memory they points to.
I'm new to C and wanted to know, what does a bitwise shift 1 << 9 in an enum definition do in this case below: ``` static enum { DEAD, LIVE } state[1 << 9]; ```
The expression1<<9is the same as 29, which is 512. So an array of 512 enums is declared.
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.Closed5 years ago.Improve this question How does gcc manage to compile printf in ANSI-C? Every printf prototype I saw used varargs, but that is not supported in ANSI-C eg: ``` int (*)(const char *, ...) ``` Is there a trick to it, if so can we use it for our code in ANSI-C?
You assumptions are all wrong. First, there is nothing called "ANSI-C" after the year 1990. Americans may refer to the C standard as INCITS/ISO/IEC 9899:2011, but nobody outside the US cares. We just call it ISO C. The C language has (unfortunately) always supported variadic functions, for the past 40 years or so. In order to code the function definition, you need to includestdarg.h. You are confusing this with variadicmacros, which were introduced in the year 1999 (C99).
What happens when I have multiple#defines with the same name in one sourcefile: for example: ``` #define Dummy 1 #define Dummy 2 ``` I do NOT intend to use it, but saw something similar in production code. Is this covered by the standard?
It's constraint violation and as such, a conforming compiler is required to issue a diagnostic. C11, 6.10.3 Macro replacementstates: An identifier currently defined as an object-like macro shall not be redefined by another #define preprocessing directive unless the second definition is an object-like macro definition and the two replacement lists are identical. [..] As noted, it's not a constraint violation if the replacement is identical. So ``` #define X 1 #define X 2 ``` requires a diagnostic; whereas ``` #define X 1 #define X 1 ``` is OK. Similar constraints apply for function-like macros (C11, 6.10.3, 2).
This question already has an answer here:Is it OK to name a variable with the same name as a structure tag?(1 answer)Closed5 years ago. In C, can a field of a struct and a variable have the same name? Are there gonna be any issues? For example: ``` struct foo { int x } main() { struct foo j; int x = 666; j.x = x; } ``` Is this valid?
In C, can a field of a struct and a variable have the same name? Yes. That's becausestructs have their own namespace.C11 §6.2.3 Name spaces of identifiers [...] Thus, there are separate name spaces for various categories of identifiers, as follows:— the members of structures or unions; each structure or union has a separate name space for its members (disambiguated by the type of the expression used to access the member via the.or->operator);— all other identifiers, called ordinary identifiers (declared in ordinary declarators or as enumeration constants).
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.Closed5 years ago.Improve this question So I used this code in order to pass a variable in to my struct: ``` strcpy(s[i].orderName, Name); ``` and it works how I want it to. However, the rest of my variables are integers and a double and it appears there is no "intcpy()" alternative from what I have found. Is there another way to pass integer and double variables in to my struct? Thank you.
You can use a simple assignment=for theintvariables: ``` struct abc { int a; int b; }; void foo(int b) { struct abc x; x.a = 8; x.b = b; printf("x.a: %d\n, x.b: %d\n", x.a, x.b); } ```
I allocated 5 bytes of memory using malloc and I was able to use those 5 bytes to store characters or integers. For example,use the first byte to store a character and the next four bytes to store an integer. How does malloc takes care of memory allignment issues?
malloc If allocation succeeds, returns a pointer to the lowest (first) byte in the allocated memory block that is suitably aligned for any object type. So the memory block is aligned for any object type. use the first byte to store a character and the next four bytes to store an integer. That's not valid. You need to either bundle the char and integer together in a structure (which might include padding) or have 2 separate memory blocks for them. Or serialize them (which is another issue).