question
stringlengths
25
894
answer
stringlengths
4
863
I am doing reverse engineer of the codebase of uC PIC16F1516 and looking for FOSC to determine TIMER overflow count value. I can see in the code, ``` // SCS FOSC; IRCF 500KHz_MF; OSCCON = 0x38; ``` And ``` #define _XTAL_FREQ 4000000 ``` May I please know the crystal oscillator frequency that the TIMER would have...
Not very clear, but I guess that FOSC (frequency of oscillator) is 4 Mhz (i.e., _XTAL_FREQ defined in the source). The OSCCON register can then divide that clock and sets other things, so look well, but your question is answered by 4 Mhz.
Input: I want to be something END. END is is that specific word. I need to store all my words. ``` do { scanf("%s", row[p]); p++; }while(strcmp(niz,'END')!=0); ``` Is this the right way ?
``` #include<stdio.h> #include<string.h> /*Description: How to scanf a string until a specific word occurs*/ int main(){ char row[6][10]; int p=0; //I want to be something END. ( 6 words for input.) printf("Please enter a word.\n"); /* do { scanf("%s", row[p]); p++; }w...
``` int a,b; while (scanf("%d",&a) != EOF){ printf("%d ",a); } printf("\n"); printf("Pls enter value b\n"); scanf("%d",&b); printf("%d",b); return 0; ``` When I type and then use command + D to jump out of the while loop, I cannot enter it again at this time, resulting in the value...
As other have suggested , you should find another way to terminate your loop. Although , here is a workaround: ``` #include <stdio.h> int main(){ int a,b; while (scanf("%d",&a)!=EOF){ printf("%d ",a); } printf("\n"); printf("Pls enter value b\n"); freopen("/dev/tty", "r", stdin); /* Chan...
What is a difference between((int) a)and(int(a))? Is the second expression valid in pure "С" (not "C" under "C++")?
There's no difference between them in C++. However, C supports only the first cast operation. See this example fromtutorial: ``` double x = 10.3; int y; y = (int) x; // c-like cast notation y = int (x); // functional notation ```
This question already has answers here:Using true and false in C(15 answers)Closed3 years ago. I thought that C interpretedtrueas1but now I'm having doubts. Full code (compiled with GCC 5.1): ``` if(true && true) // Error: 'true' undeclared (first use in this function) { } ``` Why does this happen?
trueis not a keyword in C like it is in C++. To access it you'll have to#include <stdbool.h>.
``` int ch; scanf("%c", &ch); //Read a character (%c) printf("You entered char %c %d\n", ch, ch); return 0; ``` expected output: You entered char A 65Actual output: You entered char A 32577
chis of type int andscanf("%c", &ch)copies abytein to address location pointed by&ch.MachineEndiannessdecides where thecharvalue from iostream stored. ifchon stack garbage values present in remaining bytes ofch
I am able to compile BoringSSL on Ubuntu and created libssl.a and libcrypto.a. In Makefile I have changed-Lpath to point to those library location and-lssl -lcryptoto specify the library name. However my machine already has OpenSSL installed, so looks like in this case it is the OpenSSL libs getting picked up as alway...
If you have-Lpointed to the directory where BoringSSL is built, it will always use BoringSSL instead of the system SSL (except if the linker is searching for shared libraries only, as John Bollinger points out). You'll also need to pass-pthreadto the compiler as it can't implicitly pull in the POSIX thread library wi...
The case oftypedefusage: ``` struct tagPOINT { int x; int y; }; typedef struct tagPOINT MyPoint; MyPoint point = {1, 2}; ``` You see this line code:typedef struct tagPOINT MyPoint; why thetypedefcan distinguish the code then divide tostruct tagPOINTandMyPoint, instead ofstructandtagPOINT MyPoint?
In the C grammar, the only token that can come after astructkeyword is either anidentifieror a{. If it is an identifier, it is a structure tag (which is a name for the structure). So, whenever the compiler seesstruct tagPOINT, it knowstagPOINTis a structure tag, even if it has some other meaning when it is not immedia...
I'm new to programming in C and I was looking at some code. I was wondering what the following means: ``` adjust(&total, adjustmentFactor); ``` I know thattotalandadjustmentFactorare both doubles, but since that this function does assign output to a variable, I'm assuming that the function changes what total points ...
Yes, you are right: the ampersand takes the address of an lvalue (a variable) and passes it as pointer. Youradjust()function would look like: ``` void adjust(double *a, double f) { ... do a lot of stuff *a = *a * f/2+1.0; // dummy formula that will change the content ... }; ``` So in the function ...
I have an application on z/OS USS that happily reads EBCDIC (IBM-1047) and ASCII (ISO8859-1) files that are tagged with either encoding intochar[]buffers. When started from a shell, the C runtime will automatically convert the file contents infgets()into EBCDIC for the program to use. This allows comparisons with lite...
One of the ways of controlling automatic conversion is_BPXK_AUTOCVT=ONThisarticlehere describes the issue on more detail. Here is a snippet:
I have code that needs to call sleep for both windows and linux. In an attempt to avoid placing ifdefs everywhere there is a Sleep I did the following ``` typedef Sleep sleep ``` The issue with this is windows takes Sleep in microseconds and linux takes sleep in seconds. Is there a way to do something like this pse...
No, you cannot use a typedef for this purpose. However, you can write the followingpreprocessormacro: ``` #if defined( _WIN32 ) || defined( _WIN64 ) #define MY_SLEEP_MACRO( x ) Sleep(x) #else #define MY_SLEEP_MACRO( x ) sleep((x)/1000) #endif ``` Now, in your code, you can simply callMY_SLEEP_MACRO( 5000 );in order...
I am currently exploring xv6 source code and found this line in the code of function getcmd (booklet: line 8688): ``` gets(buf, nbuf); ``` I tried to find the source for function gets in the booklet (https://pdos.csail.mit.edu/6.828/2018/xv6/xv6-rev11.pdf) and in the official repo (https://github.com/mit-pdos/xv6-pu...
Check inulib.cfile in the same repo. It is defined as ``` char* gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ cc = read(0, &c, 1); if(cc < 1) break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; return buf; } ```
I'm trying to convert theRFC 5905 NTP Short Formatto seconds. The NTP Short Format is a uint32_t with the first 16 bits being the seconds (i.e seconds = format >> 16) and the other 16 bits being the fraction of a second (i.e fraction = format & 0xFFFF). After converting I'd like the output as a double.
This answer is taken from a Google Group chat. I hope it helps:Treat it as a 32-bit fraction with the binary point at the left, multiply by a million, keep the integer part. ``` microsecs = ((unsigned long long) frac * 1000000) >> 32; ``` To round (can round up to 1000000), ``` microsecs = ((unsigned long long) fra...
When readinghttps://en.wikipedia.org/wiki/Address_space_layout_randomization, I encountered a term: Position-independent executable (PIE) implements a random base address for themain executable binaryand has been in place since 2003. It provides the same address randomness to the main executable as being used for the...
It means the output of the linker when you build your executable, the so-calleda.outfile in the *nix world. The compiler creates object files and the linker resolves all the dependencies into ana.outfile. Some of those dependencies will be external (dynamic link libraries). The main executable will be the file that t...
The case oftypedefusage: ``` struct tagPOINT { int x; int y; }; typedef struct tagPOINT MyPoint; MyPoint point = {1, 2}; ``` You see this line code:typedef struct tagPOINT MyPoint; why thetypedefcan distinguish the code then divide tostruct tagPOINTandMyPoint, instead ofstructandtagPOINT MyPoint?
In the C grammar, the only token that can come after astructkeyword is either anidentifieror a{. If it is an identifier, it is a structure tag (which is a name for the structure). So, whenever the compiler seesstruct tagPOINT, it knowstagPOINTis a structure tag, even if it has some other meaning when it is not immedia...
I'm new to programming in C and I was looking at some code. I was wondering what the following means: ``` adjust(&total, adjustmentFactor); ``` I know thattotalandadjustmentFactorare both doubles, but since that this function does assign output to a variable, I'm assuming that the function changes what total points ...
Yes, you are right: the ampersand takes the address of an lvalue (a variable) and passes it as pointer. Youradjust()function would look like: ``` void adjust(double *a, double f) { ... do a lot of stuff *a = *a * f/2+1.0; // dummy formula that will change the content ... }; ``` So in the function ...
I have an application on z/OS USS that happily reads EBCDIC (IBM-1047) and ASCII (ISO8859-1) files that are tagged with either encoding intochar[]buffers. When started from a shell, the C runtime will automatically convert the file contents infgets()into EBCDIC for the program to use. This allows comparisons with lite...
One of the ways of controlling automatic conversion is_BPXK_AUTOCVT=ONThisarticlehere describes the issue on more detail. Here is a snippet:
I have code that needs to call sleep for both windows and linux. In an attempt to avoid placing ifdefs everywhere there is a Sleep I did the following ``` typedef Sleep sleep ``` The issue with this is windows takes Sleep in microseconds and linux takes sleep in seconds. Is there a way to do something like this pse...
No, you cannot use a typedef for this purpose. However, you can write the followingpreprocessormacro: ``` #if defined( _WIN32 ) || defined( _WIN64 ) #define MY_SLEEP_MACRO( x ) Sleep(x) #else #define MY_SLEEP_MACRO( x ) sleep((x)/1000) #endif ``` Now, in your code, you can simply callMY_SLEEP_MACRO( 5000 );in order...
I am currently exploring xv6 source code and found this line in the code of function getcmd (booklet: line 8688): ``` gets(buf, nbuf); ``` I tried to find the source for function gets in the booklet (https://pdos.csail.mit.edu/6.828/2018/xv6/xv6-rev11.pdf) and in the official repo (https://github.com/mit-pdos/xv6-pu...
Check inulib.cfile in the same repo. It is defined as ``` char* gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ cc = read(0, &c, 1); if(cc < 1) break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; return buf; } ```
I'm trying to convert theRFC 5905 NTP Short Formatto seconds. The NTP Short Format is a uint32_t with the first 16 bits being the seconds (i.e seconds = format >> 16) and the other 16 bits being the fraction of a second (i.e fraction = format & 0xFFFF). After converting I'd like the output as a double.
This answer is taken from a Google Group chat. I hope it helps:Treat it as a 32-bit fraction with the binary point at the left, multiply by a million, keep the integer part. ``` microsecs = ((unsigned long long) frac * 1000000) >> 32; ``` To round (can round up to 1000000), ``` microsecs = ((unsigned long long) fra...
When readinghttps://en.wikipedia.org/wiki/Address_space_layout_randomization, I encountered a term: Position-independent executable (PIE) implements a random base address for themain executable binaryand has been in place since 2003. It provides the same address randomness to the main executable as being used for the...
It means the output of the linker when you build your executable, the so-calleda.outfile in the *nix world. The compiler creates object files and the linker resolves all the dependencies into ana.outfile. Some of those dependencies will be external (dynamic link libraries). The main executable will be the file that t...
I have code that needs to call sleep for both windows and linux. In an attempt to avoid placing ifdefs everywhere there is a Sleep I did the following ``` typedef Sleep sleep ``` The issue with this is windows takes Sleep in microseconds and linux takes sleep in seconds. Is there a way to do something like this pse...
No, you cannot use a typedef for this purpose. However, you can write the followingpreprocessormacro: ``` #if defined( _WIN32 ) || defined( _WIN64 ) #define MY_SLEEP_MACRO( x ) Sleep(x) #else #define MY_SLEEP_MACRO( x ) sleep((x)/1000) #endif ``` Now, in your code, you can simply callMY_SLEEP_MACRO( 5000 );in order...
I am currently exploring xv6 source code and found this line in the code of function getcmd (booklet: line 8688): ``` gets(buf, nbuf); ``` I tried to find the source for function gets in the booklet (https://pdos.csail.mit.edu/6.828/2018/xv6/xv6-rev11.pdf) and in the official repo (https://github.com/mit-pdos/xv6-pu...
Check inulib.cfile in the same repo. It is defined as ``` char* gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ cc = read(0, &c, 1); if(cc < 1) break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; return buf; } ```
I'm trying to convert theRFC 5905 NTP Short Formatto seconds. The NTP Short Format is a uint32_t with the first 16 bits being the seconds (i.e seconds = format >> 16) and the other 16 bits being the fraction of a second (i.e fraction = format & 0xFFFF). After converting I'd like the output as a double.
This answer is taken from a Google Group chat. I hope it helps:Treat it as a 32-bit fraction with the binary point at the left, multiply by a million, keep the integer part. ``` microsecs = ((unsigned long long) frac * 1000000) >> 32; ``` To round (can round up to 1000000), ``` microsecs = ((unsigned long long) fra...
When readinghttps://en.wikipedia.org/wiki/Address_space_layout_randomization, I encountered a term: Position-independent executable (PIE) implements a random base address for themain executable binaryand has been in place since 2003. It provides the same address randomness to the main executable as being used for the...
It means the output of the linker when you build your executable, the so-calleda.outfile in the *nix world. The compiler creates object files and the linker resolves all the dependencies into ana.outfile. Some of those dependencies will be external (dynamic link libraries). The main executable will be the file that t...
This question already has answers here:Enabling VLAs (variable length arrays) in MS Visual C++?(5 answers)Closed3 years ago. The following code wont compile. It give me an error that 'a constant size was expected'. Is there any way or a compiler flag or a preprocessor directive to add, to cause enable support for C99...
As already outlined in comments, your (obvious) options with C+MSVC would be: A macro (you can#undefit when no longer needed)alloca (shownhere), which allocates on stack and does not require explicit deallocation; you may wrap it in a macro for a convenient "create X-sized array of Y" pseudo-function As itwas answer...
To get avoid *from a function in C I would do something like this (very basic example): ``` void *get_ptr(size_t size) { void *ptr = malloc(size); return ptr; } ``` How do I achieve the same result when usingstd::unique_ptr<>?
You need to specify custom deleter in order to usevoidasunique_ptr's type argument like that: ``` #include <memory> #include <cstdlib> struct deleter { void operator()(void *data) const noexcept { std::free(data); } }; std::unique_ptr<void, deleter> get_ptr(std::size_t size) { return std::unique...
Is there a way(a C API?), using which I can get the hostname of a remote server. Something likegethostname()but having an IP address as an argument. I know aboutgetnameinfo() and getaddrinfo(), however I don't want the hostname used in the DNS server. I want the hostname which you get when you use the hostname comman...
Although you can query DNS for hostnames, there's no standard protocol to ask a machine (an interface, really) what it calls itself (if it does even have a name for itself - that's not mandatory). You'd need to implement and deploy a simple server program onto all the hosts you're interested in (it could be something...
I have anellipsewhich is drew on a window. I want to show a messagewhen the pointer is on it (on the ellipse). How I do it? Is there any event for shapes? LikeWM_MOVEorWM_SIZE. I useTDM-GCCandClanguage.
When you draw on a device context, all knowledge of what shape you draw is lost, and the system just retains the pixel by pixel information of that device context. So there is no way for the system to give you any information about the shapes that you draw because it knows nothing of those shapes. In order to do what...
Valgrind is finding memory leaks but i can't seem to pinpoint them, i'm hope-full someone here can help me: main calls areDictionary* dictionary = initDictionary();
YourinitDictionarydoesn't return the pointerdictionaryanywhere. That means when you do ``` Dictionary* dictionary = initDictionary(); ``` the value ofdictionarywill beindeterminate(seemingly random or garbage), and dereferencing this pointer or passing it tofreewill result inundefined behavior. You solve this by a...
If Iexport http_proxy, thencurlwill use the proxy automatically. Is this becausecurllooks uphttp_proxyand setup proxy internally in the source code or it just automatically works? Seems many other applications support http_proxy automatically, so I think maybe http_proxy is handled by Linux?? I'm writing an applicati...
Is this because curl looks up http_proxy and setup proxy internally in the source code or it just automatically works? curlget's the value of environment variablehttp_proxyincurl/lib/url.cand processes it. It does not work "automatically". I think maybe http_proxy is handled by Linux? No, it is not. It is explicitl...
Valgrind is finding memory leaks but i can't seem to pinpoint them, i'm hope-full someone here can help me: main calls areDictionary* dictionary = initDictionary();
YourinitDictionarydoesn't return the pointerdictionaryanywhere. That means when you do ``` Dictionary* dictionary = initDictionary(); ``` the value ofdictionarywill beindeterminate(seemingly random or garbage), and dereferencing this pointer or passing it tofreewill result inundefined behavior. You solve this by a...
If Iexport http_proxy, thencurlwill use the proxy automatically. Is this becausecurllooks uphttp_proxyand setup proxy internally in the source code or it just automatically works? Seems many other applications support http_proxy automatically, so I think maybe http_proxy is handled by Linux?? I'm writing an applicati...
Is this because curl looks up http_proxy and setup proxy internally in the source code or it just automatically works? curlget's the value of environment variablehttp_proxyincurl/lib/url.cand processes it. It does not work "automatically". I think maybe http_proxy is handled by Linux? No, it is not. It is explicitl...
Why SIZE_OF_STR returns 7 and 5 values for "hello" string? ``` #include <stdio.h> #define SIZE_OF_STR(s) sizeof(s)/sizeof(char)-1 int main() { char *x = "hello"; printf("%d\n",SIZE_OF_STR(x)); printf("%d",SIZE_OF_STR("hello")); return 0; } ``` Output: ``` 7 5 ```
The first sizeof is actually doing sizeof of a pointer to char which is 8. The second one is doing the sizeof of the constant string which yields 6 for "hello". Your macro expression actually resolves the divison before the subtraction, therefore resulting in both 8-1=7 and 6-1=5.
Can someone explain why the code prints "HelloWorld" and not "HelloWorldThere" ? Also why does it print anything at all as there are no conditions in if or switch statements ? Here is the code: ``` #include <stdio.h> int main() { int a, b; if(printf("Hello")) switch(printf("World")) whil...
Pretty straightforward:printf("Hello")returns 5 (the number of characters written). 5 is not 0, so it's considered "true" for the purposes of the if, so thenprintf("World")also returns 5, the switch looks for acase 5:, doesn't find one, and stops there.
I was reading some code and came across the following statement: ``` struct sockaddr_in server ``` I understand thatsockaddr_inis some predefinedstructbut why do we putstructas a prefix? Also shown below, a similar thing is attempted Cannot I just write: ``` sockaddr_in server ```
The syntax of the C language requires that a declaration of a variable of astructtype include thestructkeyword before the type. While C++doesallow this keyword to be omitted, C does not.
here's the code: can anyone explain this issue how can i deallocate the memory of s in main ``` char *get(int N) { char *s=malloc(10*sizeof(char)); s="hello"; return s; } int main() { char *s=get(4); printf(s); free(s); } ```
This here: ``` s="hello"; ``` Doesn't write"hello"to the allocated memory. Instead, it reassignssto point to a read-only place where"hello"is stored. The memory you allocated withmallocis leaked, and thefree(s);is invalid, because you can't free that read-only memory. If you want to copy"hello"intos, trystrcpy(s,"h...
I am solving a binary exploitation challenge on picoCTF and came across this piece of code: ``` ((void (*)())buf)(); ``` wherebufis a character array. I solved the challenge but can't seem to understand what exactly it's doing. I looked atthisthread but I couldn't make it out. What does((void (*)())buf)();mean?
void (*)()is a type, the type being "pointer to function that takes indeterminate arguments and returns no value". (void (*)())is a type-cast to the above type. (void (*)())bufcastsbufto the above type. ((void (*)())buf)()calls the function (passing no arguments). In short: It tells the compiler to treatbufas a po...
There is a .out file, which will causeAborted (core dumped)infomation when running. I want to put this informationAborted (core dumped)into a file. I want to put it into my program actually, but I have redirect problem. Once this problem solved, I can put it in my program by redirect and popen(). I try./a.out 2>fil...
Redirecting standard error fora.outwon't do anything sincea.outdoesn't actually write theAborted (core dumped)message. This message is writtenby the shell itselfin response to an abnormal status returned when it callswaitpidor similar on your process. In order to obtain the same information programmatically, you'll n...
Compiling the following program ``` int main(void) { int const c[2]; c[0] = 0; c[1] = 1; } ``` leads to error: assignment of read-only location ‘c[0]’. As I understand it, the const only applies to the location of c and so c[0] and c[1] should be mutable. Why is this error produced?
As I understand it, the const only applies to the location of c No. You can't modify the location of the array anyway. What you probably mean is if you have aint * const, then that indeed is a constant pointer to a modifiableint. However,int const c[2];is an array of 2 constant ints. As such, you have to initialize t...
``` short a = 0x1234; char *p = &a; printf("%x%x", *p, *(p+1)); output 3412 ``` I'm curious about how memory store a value 0x1234. I firstly thought 0x1234 is saved as 0x3412(reversed per byte) in memory, but according to lsb 0 numbering, it seems right that memory saves 0x1234 as 0x2c48(reversed per bit) I think th...
On a little-endian system a multi-byte word is stored in reversebyteorder. So e.g. the 16-bit word0x1234will be stored with0x34in the low address, and0x12in the high address. As a byte array it would be ``` uint8_t word[2] = { 0x34, 0x12 }; ``` Bits of a byte are never reversed. A 32-bit (four byte) word like0x...
I wonder if I can use the latest C2x features in developing a Python extension module, since the CPython itself is written partially in C89 and borrowing some features from C99.
You can do whatever you want in your own module. C as Python uses it works with both C89 compilers (MSVC) and compilers that support more modern standards (literally every other relevant C compiler today). Just don't expect your code to ever be merged into upstream Python if you violatePEP 7like that.
``` #include <stdio.h> void main() { int s = (char)1; int *p = &s; printf("%x", *p); } output 1 ``` I tried to find out if int type variable is declared and substitute for char type value 1, rest of 3 bytes of variable s is initialized or not. For this output, can I think each of 24 bits of variable s i...
What happen? The smaller type gets implicitly castbackto the larger type, so your explicit type cast does nothing effectively (except that larger values may be truncated). Functionally, these two lines are identical: ``` int x = (char) 1; int y = (int)(char) 1; ``` And these two lines are identical as well: ``` i...
Let's say I have a pseudocode and sum = 3 ``` for i = (1 to 3) sum = sum + i return sum ``` This returns 9 because 3+1=4, 4+2=6, 6+3=9 But when doing this ``` for i = (1 to 3) { sum = sum + i return sum } ``` Sum returned is 4? Why does the curly braces somehow make the for loop run only once?
Your indentation of the first loop is misleading. Unroll both and it will be apparent what's going on: ``` sum = sum + 1 sum = sum + 2 sum = sum + 3 return sum ``` This one adds 6 tosumand then returns it. ``` sum = sum + 1 return sum sum = sum + 2 return sum sum = sum + 3 return sum ``` This one adds 1 tosumand t...
Let's say I have a pseudocode and sum = 3 ``` for i = (1 to 3) sum = sum + i return sum ``` This returns 9 because 3+1=4, 4+2=6, 6+3=9 But when doing this ``` for i = (1 to 3) { sum = sum + i return sum } ``` Sum returned is 4? Why does the curly braces somehow make the for loop run only once?
Your indentation of the first loop is misleading. Unroll both and it will be apparent what's going on: ``` sum = sum + 1 sum = sum + 2 sum = sum + 3 return sum ``` This one adds 6 tosumand then returns it. ``` sum = sum + 1 return sum sum = sum + 2 return sum sum = sum + 3 return sum ``` This one adds 1 tosumand t...
Let's say I have a pseudocode and sum = 3 ``` for i = (1 to 3) sum = sum + i return sum ``` This returns 9 because 3+1=4, 4+2=6, 6+3=9 But when doing this ``` for i = (1 to 3) { sum = sum + i return sum } ``` Sum returned is 4? Why does the curly braces somehow make the for loop run only once?
Your indentation of the first loop is misleading. Unroll both and it will be apparent what's going on: ``` sum = sum + 1 sum = sum + 2 sum = sum + 3 return sum ``` This one adds 6 tosumand then returns it. ``` sum = sum + 1 return sum sum = sum + 2 return sum sum = sum + 3 return sum ``` This one adds 1 tosumand t...
I'm trying to understand the firstmicrocorruptionchallenge. I want to ask about the first line of the main function. Why would they add that address to the stack pointer?
This looks like a 16-bit ISA1, otherwise the disassembly makes no sense. 0xff9cis -100 in 16-bit 2's complement, so it looks like this is reserving 100 bytes of stack space formainto use. (Stacks grow downward on most machines).It's not an address, just a small offset. SeeMSP430 Assembly Stack Pointer Behaviorfor a...
This question already has answers here:why is -1>strlen(t) true in C? [duplicate](3 answers)Closed3 years ago. I got here an actually "easy" C code Block but my compiler gives me an other result as expected. ``` int a; int c; unsigned int b; a = b = 10; c = -1; if(a+b > c) printf("True\n"); else printf("Fals...
To be able to compare the result ofa+bandcthen they need to be the same type. Becausebis unsigned then the result ofa + bis also unsigned. This means that either that result, orc, must be converted. The conversion will be thatcis converted (throughpromotion) to anunsigned intand then-1becomes a very large value (4294...
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed3 years ago.Improve this question So I'm trying to fin...
Don't see anything wrong with python: ``` >>> 1.25 / (2 * 10**-12) 625000000000.0 ```
Is there any way to dynamically allocate memory for a structure in the definition of the structure, and if it can't be done, what is the best way to dynamically allocate memory for that structure ? ``` typedef struct user_t{ char user_name[30]; char email[50]; int movieswatched; movie *movielist; }use...
You can use aflexible array member: ``` typedef struct user_t{ char user_name[30]; char email[50]; int movieswatched; movie movielist[]; // The flexible array member, // must always be last and declared as an array without a size }user_t; ``` A structure like this must be all...
While developing my FreeRTOS application targeting an ARM Cortex M3 with GCC, using the C99 dialect, I decided to use strnlen, assuming that it's a standard C function and that I just need to include to use it. The compiler warns me of an implicit declaration for strnlen, making me realize it's not part of the C99 st...
Just implement it yourself, without a particular header. ``` size_t strnlen(const char *s, size_t maxlen) { size_t len = 0; if(s) for(char c = *s; (len < maxlen && c != '\0'); c = *++s) len++; return len; } ```
I am trying to write a program that converts a given decimal value to IEEE representation of 32-bit Hex value. For example: Input:1.0, Output:0x3f800000 I store the value in a variable like the following: ``` float a = 1.0; ``` The compiler actually does the conversion of1.0to a Hex value. Is it possible to get the...
``` float a = 1.0; uint8_t *hexbytes = (uint8_t *)&a; printf("0x%02X%02X%02X%02X\r\n", hexbytes[0], hexbytes[1], hexbytes[2], hexbytes[3]); ```
I have a variable with type double and I want to set it with a integer value. For example: ``` double x; ``` In GDB, when I do : ``` set x = 14 p x $1 = 14 //ok, looks right x/xg &x 0x7fffffffec28: 0x402c000000000000 //oh no, this is a double representation and I want integer! ``` What I want is toxhave an intege...
You can cast the type of the memory location: ``` p {int}&x=10 $4 = 10 x/xg &x 0x7f2c40 <x>: 0x000000000000000a ```
Is there any way to dynamically allocate memory for a structure in the definition of the structure, and if it can't be done, what is the best way to dynamically allocate memory for that structure ? ``` typedef struct user_t{ char user_name[30]; char email[50]; int movieswatched; movie *movielist; }use...
You can use aflexible array member: ``` typedef struct user_t{ char user_name[30]; char email[50]; int movieswatched; movie movielist[]; // The flexible array member, // must always be last and declared as an array without a size }user_t; ``` A structure like this must be all...
While developing my FreeRTOS application targeting an ARM Cortex M3 with GCC, using the C99 dialect, I decided to use strnlen, assuming that it's a standard C function and that I just need to include to use it. The compiler warns me of an implicit declaration for strnlen, making me realize it's not part of the C99 st...
Just implement it yourself, without a particular header. ``` size_t strnlen(const char *s, size_t maxlen) { size_t len = 0; if(s) for(char c = *s; (len < maxlen && c != '\0'); c = *++s) len++; return len; } ```
I am trying to write a program that converts a given decimal value to IEEE representation of 32-bit Hex value. For example: Input:1.0, Output:0x3f800000 I store the value in a variable like the following: ``` float a = 1.0; ``` The compiler actually does the conversion of1.0to a Hex value. Is it possible to get the...
``` float a = 1.0; uint8_t *hexbytes = (uint8_t *)&a; printf("0x%02X%02X%02X%02X\r\n", hexbytes[0], hexbytes[1], hexbytes[2], hexbytes[3]); ```
I have a variable with type double and I want to set it with a integer value. For example: ``` double x; ``` In GDB, when I do : ``` set x = 14 p x $1 = 14 //ok, looks right x/xg &x 0x7fffffffec28: 0x402c000000000000 //oh no, this is a double representation and I want integer! ``` What I want is toxhave an intege...
You can cast the type of the memory location: ``` p {int}&x=10 $4 = 10 x/xg &x 0x7f2c40 <x>: 0x000000000000000a ```
I'm trying to map device memory residing on 64-bit address into 32-bit process on 64-bit OS. I'm using the following lines ``` baseaddr = addr & ~(sysconf(_SC_PAGE_SIZE) - 1); fd = open("/dev/mem", O_RDONLY | O_SYNC); base_ptr = mmap(0, 4096, PROT_READ, MAP_PRIVATE, fd, baseaddr); ``` baseaddr is uint64_t and is hig...
You should be usingmmap64here. The address has to be mapped into an area that a 32-bit process can use. However, Istronglyadvise that you get a true 64-bit version of this application. You're heading down a rabbit-hole here and there's a lot of rabbit-poo in that hole, if you catch my drift ...
I have an application, which has been compiled several libraries into it through static link. And this application will load a plugin through dlopen when it runs. But it seems that the plugin can't resolve the symbol in the application, which I can find them through "nm". So what can I do? Recompile the libraries i...
You have to use the gcc flag-rdynamicwhen linking your application, which exports the symbols of the application for dynamic linkage with shared libraries. From the gcc documentation: Pass the flag -export-dynamic to the ELF linker, on targets that support it. This instructs the linker to add all symbols, not only u...
According to the Linux manual pages1and2, the functionsysloghas two different function declarations as follows: int syslog(int type, char *bufp, int len); void syslog(int priority, const char *format, ...); However, other than C++, there is no function overloading in C. How to explain the fact?
One is defined in section 2 (syslog(2)) of the manual pages (*), thus a system call. The other one is from section 3 (syslog(3)) thus a C library function. So "technically" they are different functions that happen to have the same name (albeit they are related of course, as (3) is using (2)). (*) Seemanual page sect...
I am writing a program, and I just have to check: can I name a variableoutputorinput? for example: ``` int output; int input; ``` or is this a pre-assigned name for something else? The modules I'm importing for my program are: ``` #include <pwd.h> #include <fcntl.h> #include <stdio.h> #include <signal.h> #include <...
If there are collisions between your variables and any reserved words, the compiler will inform you with a warning or an error in compilation. So if the compilation doesn't produce any error, the names you assign the variables are good.
This question already has answers here:What does the comma operator , do?(8 answers)Closed3 years ago. ``` int i = -5 , m,k=7; m=2*(++i , k-=4); printf("%d %d %d\n",i,m,k); ``` In this code the output is: [-4 6 3] but, I didn't quite understand where 6 comes from, can anyone help me?
k -= 4"returns" 3. The comma operator returns the second value which is3. Then you multiply2by3. ``` m = 2 * (++i, k -= 4) m = 2 * (-4, 3) m = 2 * 3 m = 6 ```
I'm trying to access the whole array from a struct in a function, to compare two elements for no duplication. However, I am receiving anexpected expression errorinqueue.id[]. ``` int count = sizeof(queue.id[]) / sizeof(queue.id[0]); ```
``` int count = sizeof(queue.id[]) / sizeof(queue.id[0]); ``` should be ``` int count = sizeof(queue.id) / sizeof(queue.id[0]); ```
``` #version 120 #extension GL_EXT_gpu_shader4 : enable varying vec4 texcoord; uniform sampler2D gcolor; uniform sampler2D gnormal; uniform sampler2D gdepth; const int RGBA16 = 1; const int gcolorFormat = RGBA16; void main(){ vec3 finalComposite = texture2D(gcolor, texcoord.st).rgb; vec3 finalCompositeNor...
Try ``` const int RGBA16 = 1; const int gcolorFormat = 1; ``` And if that still mysteriously destroys your framerate, just use #define instead. ``` #define RGBA16 1 #define gcolorFormat RGBA16 ```
So I am trying to follow along with the "snmpdemoapp" on the Net-SNMP website and I am getting the LINK2019 error when trying to use: ``` init_snmp("snmpdemoapp"); ``` Link to demo app:http://net-snmp.sourceforge.net/wiki/index.php/TUT:Simple_Application If I comment this line out, then it will build successfully. ...
Fixed the error by including: ``` #pragma comment(lib, "Ws2_32.lib") #pragma comment(lib, "netsnmp.lib") #pragma comment(lib, "netsnmpagent.lib") #pragma comment(lib, "netsnmpmibs.lib") #pragma comment(lib, "netsnmptrapd.lib") #pragma comment(lib, "Advapi32.lib") ```
I was trying to use code generated by STM32CubeMX. I've generated project for SW4STM32, but I have problem with iks01a2_conf_template.h file. Im supposed to replace the header file names with the ones of the target platform and rename the file to iks01a2_conf. There are 3 headers: ``` #include "stm32yyxx_hal.h" #inc...
Look intoincproject folder. Your files shuold be there. Add this folder to the include directories in your project settings or makefile
``` #version 120 #extension GL_EXT_gpu_shader4 : enable varying vec4 texcoord; uniform sampler2D gcolor; uniform sampler2D gnormal; uniform sampler2D gdepth; const int RGBA16 = 1; const int gcolorFormat = RGBA16; void main(){ vec3 finalComposite = texture2D(gcolor, texcoord.st).rgb; vec3 finalCompositeNor...
Try ``` const int RGBA16 = 1; const int gcolorFormat = 1; ``` And if that still mysteriously destroys your framerate, just use #define instead. ``` #define RGBA16 1 #define gcolorFormat RGBA16 ```
So I am trying to follow along with the "snmpdemoapp" on the Net-SNMP website and I am getting the LINK2019 error when trying to use: ``` init_snmp("snmpdemoapp"); ``` Link to demo app:http://net-snmp.sourceforge.net/wiki/index.php/TUT:Simple_Application If I comment this line out, then it will build successfully. ...
Fixed the error by including: ``` #pragma comment(lib, "Ws2_32.lib") #pragma comment(lib, "netsnmp.lib") #pragma comment(lib, "netsnmpagent.lib") #pragma comment(lib, "netsnmpmibs.lib") #pragma comment(lib, "netsnmptrapd.lib") #pragma comment(lib, "Advapi32.lib") ```
I was trying to use code generated by STM32CubeMX. I've generated project for SW4STM32, but I have problem with iks01a2_conf_template.h file. Im supposed to replace the header file names with the ones of the target platform and rename the file to iks01a2_conf. There are 3 headers: ``` #include "stm32yyxx_hal.h" #inc...
Look intoincproject folder. Your files shuold be there. Add this folder to the include directories in your project settings or makefile
I wrote a simple Linux kernel module to issuehltinstruction ``` #include <linux/kernel.h> #include <linux/module.h> MODULE_LICENSE("GPL"); static int __init test_hello_init(void) { asm("hlt"); return 0; } static void __exit test_hello_exit(void) { } module_init(test_hello_init); module_exit(test_hello_exit...
HLTdoesn't stop your machine, only make that core sleep (in C1 idle) until the next interrupt. You can try addingcliinstruction beforehlt, so only an NMI can wake that CPU up and make the function return. ``` static int __init test_hello_init(void) { asm("cli"); asm("hlt"); return 0; } ```
I am creating a small project where at first the program checks if the file is empty. If the file is empty, it skips thewhileloop as normal. However, when the file is not empty it is still skipping thewhileloop. ``` read_list = fopen("list.txt", "r"); long fileSize = 0; fseek(read_list, 0, SEEK_END); fileSize = ftell...
Rewind the file ``` rewind(read_list); //reading loop ```
Is therestringinCCS? Can I use: ``` string myString = "My String"; // Error ``` orNOT?
The standardstring.hheader file doesnotdefine a data type calledstring, it provides functions for manipulating C-style strings, which are null-terminated character arrays. For example, you can do something like: ``` #include <stdio.h> #include <string.h> int main(void) { char *myName = "paxdiablo"; printf("L...
Here's the example code. ``` #define A 100 #define B A+1 ``` I've been reading C basic books and the writer said that code could cause fatal problems and there is no explanation about it. why this code has a problem? I want to understand
Suppose you try to write: ``` int foo = B * 10; ``` You probably expect this to setBto1010. But it will actually set it to110because it expands to ``` int foo = 100+1 * 10; ``` Because of operator precedence, the multiplication is done first, so it's100 + 10, not101 * 10. To prevent problems like this, you should...
So I'm trying to do a little test project and I was watching a tutorial on how I could make part of the code, the problem is, on the video the user uses C++ and I'm working on C. I tried figuring it out and searching a bit, but it's still quite confusing to me. So the piece of code I can't understand is this: ``` pa...
Templates don't exist in C, so you need to make a custom type, like this: ``` struct pair_int_int { int first; int second; }; ``` Then return it like this: ``` return (struct pair_int_int){line, column}; ```
So Microsoft's MSVC from Visual Studio 2019 doesn't support C99 (or later), but it does support C89 and some constructs from C99. Is there an option for the GCC C-compiler (not C++-compiler) to use a standard that would guarantee that the source can also be compiled with MSVC? If it compiles with-std=iso9899:199409 -...
Is there a reason you need to care if MSVC can compile it? GCC ("mingw") can target Windows PE object files with ABI compatible with MSVC, so users could build with that, or you could even ship them binary object files/library files to use so they don't need any tooling. Policing your code base for compatibility with...
I wrote a simple Linux kernel module to issuehltinstruction ``` #include <linux/kernel.h> #include <linux/module.h> MODULE_LICENSE("GPL"); static int __init test_hello_init(void) { asm("hlt"); return 0; } static void __exit test_hello_exit(void) { } module_init(test_hello_init); module_exit(test_hello_exit...
HLTdoesn't stop your machine, only make that core sleep (in C1 idle) until the next interrupt. You can try addingcliinstruction beforehlt, so only an NMI can wake that CPU up and make the function return. ``` static int __init test_hello_init(void) { asm("cli"); asm("hlt"); return 0; } ```
I am creating a small project where at first the program checks if the file is empty. If the file is empty, it skips thewhileloop as normal. However, when the file is not empty it is still skipping thewhileloop. ``` read_list = fopen("list.txt", "r"); long fileSize = 0; fseek(read_list, 0, SEEK_END); fileSize = ftell...
Rewind the file ``` rewind(read_list); //reading loop ```
Is therestringinCCS? Can I use: ``` string myString = "My String"; // Error ``` orNOT?
The standardstring.hheader file doesnotdefine a data type calledstring, it provides functions for manipulating C-style strings, which are null-terminated character arrays. For example, you can do something like: ``` #include <stdio.h> #include <string.h> int main(void) { char *myName = "paxdiablo"; printf("L...
Here's the example code. ``` #define A 100 #define B A+1 ``` I've been reading C basic books and the writer said that code could cause fatal problems and there is no explanation about it. why this code has a problem? I want to understand
Suppose you try to write: ``` int foo = B * 10; ``` You probably expect this to setBto1010. But it will actually set it to110because it expands to ``` int foo = 100+1 * 10; ``` Because of operator precedence, the multiplication is done first, so it's100 + 10, not101 * 10. To prevent problems like this, you should...
So I'm trying to do a little test project and I was watching a tutorial on how I could make part of the code, the problem is, on the video the user uses C++ and I'm working on C. I tried figuring it out and searching a bit, but it's still quite confusing to me. So the piece of code I can't understand is this: ``` pa...
Templates don't exist in C, so you need to make a custom type, like this: ``` struct pair_int_int { int first; int second; }; ``` Then return it like this: ``` return (struct pair_int_int){line, column}; ```
So Microsoft's MSVC from Visual Studio 2019 doesn't support C99 (or later), but it does support C89 and some constructs from C99. Is there an option for the GCC C-compiler (not C++-compiler) to use a standard that would guarantee that the source can also be compiled with MSVC? If it compiles with-std=iso9899:199409 -...
Is there a reason you need to care if MSVC can compile it? GCC ("mingw") can target Windows PE object files with ABI compatible with MSVC, so users could build with that, or you could even ship them binary object files/library files to use so they don't need any tooling. Policing your code base for compatibility with...
I am making a snake game in C usingwinbgilibrary. I have a problem with functionsettextstyle(). Every call of function adds memory to the heap (about 50kb). I have to use this function in loop, so at some point the heap starts to overflow. Is there a way to release memory occupied by this function? Or some other way t...
Pull the latest winbgi sources fromhere. There was a bug (missing call toDeleteObject()afterSelectObject()to set a new font inset_font()) withintext.cxxwhich the code linked fixes.
I tried to understand the logic behind it but couldn't. What is happening behind the scene and how it's going on for infinite times? ``` char j=1; while(j <= 255) { printf("%d", j); j = j+1; } ```
In Ccharmay be signed or unsigned - that is implementation dependent. Ifsigned, then the range (on most platforms) is -128 to +127 so always less than 255. Changing the type as follows: ``` unsigned char j=1; ``` will remove the ambiguity. But even thenj <= 255will always be true on most common platforms because i...
I want to test huge memory page allocation on Linux. Just to have another method up in the sleeve. But my test simply fails to compile. ``` pa = mmap(0, 1024*1024*2, PROT_READ, MAP_PRIVATE|MAP_HUGETLB, -1, 0) ``` Produces: ``` error: use of undeclared identifier 'MAP_HUGETLB' ``` Ideally I wish to mmap a file. But...
You have to#define _GNU_SOURCEbefore#include <sys/mman.h>because this is a nonstandard flag.
I am making a snake game in C usingwinbgilibrary. I have a problem with functionsettextstyle(). Every call of function adds memory to the heap (about 50kb). I have to use this function in loop, so at some point the heap starts to overflow. Is there a way to release memory occupied by this function? Or some other way t...
Pull the latest winbgi sources fromhere. There was a bug (missing call toDeleteObject()afterSelectObject()to set a new font inset_font()) withintext.cxxwhich the code linked fixes.
I tried to understand the logic behind it but couldn't. What is happening behind the scene and how it's going on for infinite times? ``` char j=1; while(j <= 255) { printf("%d", j); j = j+1; } ```
In Ccharmay be signed or unsigned - that is implementation dependent. Ifsigned, then the range (on most platforms) is -128 to +127 so always less than 255. Changing the type as follows: ``` unsigned char j=1; ``` will remove the ambiguity. But even thenj <= 255will always be true on most common platforms because i...
I want to test huge memory page allocation on Linux. Just to have another method up in the sleeve. But my test simply fails to compile. ``` pa = mmap(0, 1024*1024*2, PROT_READ, MAP_PRIVATE|MAP_HUGETLB, -1, 0) ``` Produces: ``` error: use of undeclared identifier 'MAP_HUGETLB' ``` Ideally I wish to mmap a file. But...
You have to#define _GNU_SOURCEbefore#include <sys/mman.h>because this is a nonstandard flag.
I have twouint64variablesvar_1andvar_2and I want to set the bits ofvar_1according to the low-order6bits ofvar_2. How can I do this in C language?
Like so: ``` uint64_t mask = 0x3F; var_1 &= (~mask); var_1 |= (var_2 & mask); ```
Let's say I write this snippet: ``` #include<stdio.h> int main() { int elements; printf("enter number of elements for array\n"); scanf("%d", &elements); int arr[elements]; } ``` And I dynamically allocate memory for an array bymalloc, whats the difference besides thatmallocallocates memory in heap?....
There are two main points: mallocwill usually align memory tosizeof(max_align_t)bytes while allocation on the stack won't.Allocation on the stack can cause stack overflow while allocation withmallocshould return an error upon memory overuse.You are allowed to return a pointer returned bymallocbut not a pointer from a...
This question already has answers here:C: printf a float value(7 answers)Closed3 years ago. I just made this code: ``` #include <stdio.h> #include <stdlib.h> #define PI 3.1416 int main (){ float x; x = PI; printf("x equals: %i.\n",x); system("pause"); return 0; } ``` and the 'Pi' number is 5...
You're using the%iformat specifier forprintf. This is for signed integers. Instead use%fasxis afloat.
FILE *fopen(const char *filename, const char *mode); I saw that some people only put the name of the file inside the "filename" part, some others put the entire path example FILE *fopen("mytext.txt", r);FILE *fopen("/myfolder/mytext.txt", r); which is the correct one?
If the file is in current directory when you run the program - no. If it's not - yes, you will need to specify the path (absolute or relative to current directory)
This question already has answers here:Error with clrscr() on Dev C++ 5.4.2(6 answers)"UNDEFINED REFRENCE TO clrscr();" [duplicate](2 answers)Closed3 years ago. ``` #include<stdio.h> #include<conio.h> void main() { int i; clrscr(); printf("Enter the number to be displayed"); scanf("%d",&i); ...
<conio.h>is a non-standard header provided by Borland and a handful of other compilers and libc implementations. Dev C++ typically uses one of the Windows GCC ports, which don't provide any implementation of those functions. If you want to use some sort ofclrscrfunction in both you're going to have to come up with a ...
There are two main ways of defining structs: ``` struct triangle_s { int a,b,c; }; ``` and ``` typedef struct triangle_s { int a,b,c; } triangle; ``` It has been asked many times but every answer is about not having to writestructso many times when using thetypedefvariant. Is there a real difference other ...
There is no difference,typedefjust removes the requirement to prefix variable declarations withstruct. Whether or not totypedefstructs by default is a religious war fought mostly by people with too much time on their hands. When working inside an existing code base you should do whatever the coding standard or the su...
How can you get a custom-sized integer data type? Is there any other answer than using<stdint.h>types likeuint16_tanduint32_tand are these types platform-independent?
The answer ismostlyNo.<stdint.h>provides integers of specific sizes available on a given platform,but there's no standard way to get, say, a 20-bit integerbut you can specify arbitrary sizesmallerthan those provided by<stdint.h>by using bitfields. The following provides a 20-bit unsigned int that works as you would ex...
I have twouint64variablesvar_1andvar_2and I want to set the bits ofvar_1according to the low-order6bits ofvar_2. How can I do this in C language?
Like so: ``` uint64_t mask = 0x3F; var_1 &= (~mask); var_1 |= (var_2 & mask); ```
Let's say I write this snippet: ``` #include<stdio.h> int main() { int elements; printf("enter number of elements for array\n"); scanf("%d", &elements); int arr[elements]; } ``` And I dynamically allocate memory for an array bymalloc, whats the difference besides thatmallocallocates memory in heap?....
There are two main points: mallocwill usually align memory tosizeof(max_align_t)bytes while allocation on the stack won't.Allocation on the stack can cause stack overflow while allocation withmallocshould return an error upon memory overuse.You are allowed to return a pointer returned bymallocbut not a pointer from a...
This question already has answers here:C: printf a float value(7 answers)Closed3 years ago. I just made this code: ``` #include <stdio.h> #include <stdlib.h> #define PI 3.1416 int main (){ float x; x = PI; printf("x equals: %i.\n",x); system("pause"); return 0; } ``` and the 'Pi' number is 5...
You're using the%iformat specifier forprintf. This is for signed integers. Instead use%fasxis afloat.
I'm a University student and I'm trying to verify different printf output through the following code: ``` #include <stdio.h> int main() { int i=3,j=0; float x=5,y; printf("1: %d\n", i); printf("2: %d\n", i/j); printf("3: %d\n", i*i); printf("4: i = \n"); i=i + j; pr...
i / jis3 / 0, and integer division by 0 in C is Undefined Behavior, which means that literally anything can happen. In your case, "literally anything" meant "go back in timeand make the previousprintfnot work, then crash" (this actually happened due to how buffering works, but that's just an implementation detail).
Is there any other way of passing user's parameters into a program other than through ./program argument1 argument2 whereargument1andargument2will be passed on tomain'sargv[]?
Your application could read the values from the standard input, a configuation file or even environnent variables.
I'm using theVIPS libraryfor manipulating images and adding text to them. I want to know how to add spacing to characters in text? The following image is an example of what I'm talking about.
You can usepango markup. For example: ``` vips text x.png '<span letter_spacing="10000">Hello!</span>' --dpi 300 ``` To make: