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 to use to overflow count computation?
|
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++;
}while(strcmp(row[p],"END")!=0);
//Above loop runs forever(or until row runs out of space), because p increments after info is read
*/
do
{
scanf("%s", row[p]);
p++;
}while(strcmp(row[p-1],"END")!=0);
//This loop ends once string just read in from keyboard/user equals "END"
return 0;
}
```
|
```
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 of b being random.
|
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); /* Change /dev/tty to con: if you are using windows */
scanf("%d",&b);
printf("%d",b);
return 0;
}
```
You can use freopen to force input from the console.
|
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 always because the libraries have exact same name.
If there any other way to enforce OS to use BoringSSL other than completely remove or disable OpenSSL and try?
|
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 with a static library like it can with a shared library.
|
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 immediately afterstruct.
|
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 to? If that's what it does, how would you change it if you were to implement adjust?
|
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 you'd use*aevery time you'd want to use the value pointed at by the first argument, and everytim you want to assign a new value to the original variable.
|
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 literals encoded natively in EBCDIC.
However, when the program is run via Jenkins (Java JVM 1.8), the automatic conversion is suppressed andfgets()returns data unchanged, so ASCII. I have tried supplying every environment variable in the user's.profileand/etc/profileto the JVM, and verified that they are in the program'senvp.
Does anyone know where the control of this function is documented or available?
|
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 pseudo-code.
```
typedef Sleep(x) sleep(x/1000)
```
|
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 to wait 5 seconds on both platforms.
|
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-public) but didn't manage to do that. Can you please provide me a link or explain why there is no source for the function gets?
|
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) frac * 1000000 + (1LL<<31)) >> 32;
```
|
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 shared libraries.
What doesmain executable binarymean here? Is it just a tu/source file that contains the main function?
|
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 the os (possibly the linker) loads initially when you execute it. Subsequent loads would be the dynamic link libraries that are external dependencies created during the build process.
|
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 immediately afterstruct.
|
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 to? If that's what it does, how would you change it if you were to implement adjust?
|
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 you'd use*aevery time you'd want to use the value pointed at by the first argument, and everytim you want to assign a new value to the original variable.
|
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 literals encoded natively in EBCDIC.
However, when the program is run via Jenkins (Java JVM 1.8), the automatic conversion is suppressed andfgets()returns data unchanged, so ASCII. I have tried supplying every environment variable in the user's.profileand/etc/profileto the JVM, and verified that they are in the program'senvp.
Does anyone know where the control of this function is documented or available?
|
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 pseudo-code.
```
typedef Sleep(x) sleep(x/1000)
```
|
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 to wait 5 seconds on both platforms.
|
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-public) but didn't manage to do that. Can you please provide me a link or explain why there is no source for the function gets?
|
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) frac * 1000000 + (1LL<<31)) >> 32;
```
|
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 shared libraries.
What doesmain executable binarymean here? Is it just a tu/source file that contains the main function?
|
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 the os (possibly the linker) loads initially when you execute it. Subsequent loads would be the dynamic link libraries that are external dependencies created during the build process.
|
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 pseudo-code.
```
typedef Sleep(x) sleep(x/1000)
```
|
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 to wait 5 seconds on both platforms.
|
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-public) but didn't manage to do that. Can you please provide me a link or explain why there is no source for the function gets?
|
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) frac * 1000000 + (1LL<<31)) >> 32;
```
|
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 shared libraries.
What doesmain executable binarymean here? Is it just a tu/source file that contains the main function?
|
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 the os (possibly the linker) loads initially when you execute it. Subsequent loads would be the dynamic link libraries that are external dependencies created during the build process.
|
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 features such as the VLAs.
```
#include "Window.h"
#include <stdio.h>
int main( int argc, char** argv)
{
const int size = 1024 ;
char filename[size];
}
```
|
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 answeredon now-dead Microsoft Connect, MSVC does not support C99 VLAs as such, which likely didn't change since then.
|
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_ptr<void, deleter>(std::malloc(size));
}
#include <cstdio>
int main() {
const auto p = get_ptr(1024);
std::printf("%p\n", p.get());
}
```
|
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 command in linux. I have a feeling that it might be impossible to do without knowing the login credentials of that remote server but I'm not sure about it.
|
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 as simple as adding a line to/etc/inetd.confto run/bin/hostnameif it's a Unix-like system), and a client library to access it.
|
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 you want you need to keep track in your program of the high level logic of where your shapes are. Then when you handle mouse messages you can map them onto your own data structures that represent the shapes.
|
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 adding a simple
```
return dictionary;
```
at the end of theinitDictionaryfunction.
If your compiler doesn't warn you about not returning anything from the function, you need to enable more verbose warnings. UsinggccorclangI recommend the options-Wall -Wextra -Wpedanticwhen building. For MSVC use/W4.
|
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 application that needs to support proxy(http_proxy ENV), and wondering should I handle http_proxy in the source code.
|
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 explicitly handled by curl.
wondering should I handle http_proxy in the source code.
You can keep compatibility with other tools likecurland supporthttp_proxyenvironment variable in your application.
|
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 adding a simple
```
return dictionary;
```
at the end of theinitDictionaryfunction.
If your compiler doesn't warn you about not returning anything from the function, you need to enable more verbose warnings. UsinggccorclangI recommend the options-Wall -Wextra -Wpedanticwhen building. For MSVC use/W4.
|
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 application that needs to support proxy(http_proxy ENV), and wondering should I handle http_proxy in the source code.
|
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 explicitly handled by curl.
wondering should I handle http_proxy in the source code.
You can keep compatibility with other tools likecurland supporthttp_proxyenvironment variable in your application.
|
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"))
while(printf("There"))
{
return 0;
}
}
```
|
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,"hello");instead.
|
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 pointer to a function, and to call that function.
|
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>file, but it doesn't work.
|
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 need to check the exit code which will be present in$?. Signal 11 (SIGSEGV) will result in exit code 128+11=139; SIGABRT (signal 6) should result in exit code 134.
|
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 them when you declare the array:
```
int const c[2] = {0, 1};
```
In constrast:
```
int main(void) {
int c[2];
int* const foo = c;
foo[0] = 0;
foo[0] = 1;
//foo = malloc(sizeof(int)); doesn't work, can't modify foo, as it's constant
}
```
|
```
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 that the value 0x1234 is saved in memory as 0x2c48 and little-endian cpu regards 0x2c48 as 0x1234. Is this correct?
|
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 like0x12345678would be stored in the order0x78,0x56,0x34and0x12(low to high address).
|
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 is initialized as 0?
|
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:
```
int x = (char) 257; // Truncated to 1
int y = 1;
```
|
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 then returns it. Areturnstatement ends execution of the function (even if there's more statements after it, or it's inside a loop).
|
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 then returns it. Areturnstatement ends execution of the function (even if there's more statements after it, or it's inside a loop).
|
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 then returns it. Areturnstatement ends execution of the function (even if there's more statements after it, or it's inside a loop).
|
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 detailed example of MSP430 stack layout and usage.
Footnote 1: MSP430 possibly?http://mspgcc.sourceforge.net/manual/x82.htmlit's a 16-bit ISA with those register names, andthose mnemonics, and I think its machine code uses variable-length 2 or 4 byte instructions.
It's definitely not ARM;callandjmpare not ARM mnemonics; that would beblandb. Also, ARM usesop dst, src1, src2syntax, while this disassembly usesop src, dst.
|
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("False\n");
```
In my opinion a + b = 20 and its always more than -1 but why is it false?
|
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 (4294967295on most systems).20 > 4294967295is false.
|
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 find the result of1.25 ÷ (2 ✕ 10^-12).
I first tried doing it with python, but the result was too big it returned a negative number.
So I tried doing it in C, using along double, but it's still not enough.
PS. I'm using GCC v9.2.1 on Linux Ubuntu
|
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;
}user_t;
```
I want to allocate memory for movielist .
|
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 allocated dynamically (with e.g.malloc), for example as
```
user_t *my_user = malloc(sizeof *my_user + sizeof(movie) * 50); // Allocate space for 50 movies
```
|
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 standard. However, since there hasn't been any linker errors, I assume the function does exist somewhere..
What header am I supposed to include in order to use strnlen, if it's not string.h? Most websites online and the man page for strnlen mention including string.h as the header
|
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 Hex value somehow from inside the C program?
|
```
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 integer valuex = 0xeinstead of a double representation even if the variable is a double.
Thanks in advance!
|
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;
}user_t;
```
I want to allocate memory for movielist .
|
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 allocated dynamically (with e.g.malloc), for example as
```
user_t *my_user = malloc(sizeof *my_user + sizeof(movie) * 50); // Allocate space for 50 movies
```
|
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 standard. However, since there hasn't been any linker errors, I assume the function does exist somewhere..
What header am I supposed to include in order to use strnlen, if it's not string.h? Most websites online and the man page for strnlen mention including string.h as the header
|
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 Hex value somehow from inside the C program?
|
```
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 integer valuex = 0xeinstead of a double representation even if the variable is a double.
Thanks in advance!
|
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 higher than 4GB.
and I compile with-D_FILE_OFFSET_BITS=64.
When I run the program it returnsEINVAL.
It worked before without the-D_FILE_OFFSET_BITS=64, but it'd only use the lower 32-bits of baseaddr - that I conclude by output of pmap -d showing the lower 32-bits of my desired address.
Any ideas what am I doing wrong?
|
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 into shared mode, and link them to the plugin?
|
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 used ones, to the dynamic symbol table. This option is needed for some uses of dlopen or to allow obtaining backtraces from within a program.
This should eliminate your problem.
|
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 sections.
|
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 <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <setjmp.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <readline/history.h>
#include <readline/readline.h>
```
|
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 finalCompositeNormal = texture2D(gnormal, texcoord.st).rgb;
vec3 finalCompositeDepth = texture2D(gdepth, texcoord.st).rgb;
gl_FragData[0] = vec4(finalComposite, 1.0);
gl_FragData[1] = vec4(finalCompositeNormal, 1.0);
gl_FragData[2] = vec4(finalCompositeDepth, 1.0);
}
```
after i added
const int RGBA16 = 1;
const int gcolorFormat = RGBA16;
it destroyed my frame rate how can i optimize this ?
|
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. I am also using Visual Studio 2015. I have the Net-SNMP library in my references. I am also not using the library in a "main()" function.
|
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"
#include "nucleo_xyyyzz_bus.h"
#include "nucleo_xyyyzz_errno.h"
```
I changed first one to "stm32f1xx_hal.h", but I don't know what to do with rest of them. I've tried several names but none of them were found.What are the header files i'm supposed to use there?My hardware is: STM32F103RB and X-NUCLEO-IKS01A2. When it comes to expansion board i need to use LPS22HB barometer to measure pressure and temperature.
|
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 finalCompositeNormal = texture2D(gnormal, texcoord.st).rgb;
vec3 finalCompositeDepth = texture2D(gdepth, texcoord.st).rgb;
gl_FragData[0] = vec4(finalComposite, 1.0);
gl_FragData[1] = vec4(finalCompositeNormal, 1.0);
gl_FragData[2] = vec4(finalCompositeDepth, 1.0);
}
```
after i added
const int RGBA16 = 1;
const int gcolorFormat = RGBA16;
it destroyed my frame rate how can i optimize this ?
|
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. I am also using Visual Studio 2015. I have the Net-SNMP library in my references. I am also not using the library in a "main()" function.
|
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"
#include "nucleo_xyyyzz_bus.h"
#include "nucleo_xyyyzz_errno.h"
```
I changed first one to "stm32f1xx_hal.h", but I don't know what to do with rest of them. I've tried several names but none of them were found.What are the header files i'm supposed to use there?My hardware is: STM32F103RB and X-NUCLEO-IKS01A2. When it comes to expansion board i need to use LPS22HB barometer to measure pressure and temperature.
|
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);
```
Loading this module on my Virtual Machine, I don't see my VM is halted.
Am I missing something?
|
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(read_list);
if (fileSize != 0) {
char line[256];
while (fgets(line, sizeof(line), read_list)) {
printf("%s", line);
}
}
```
|
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("Length of '%s' is %zu\n", myName, strlen(myName));
return 0;
}
```
Note the string in that code, it's a pointer to thepaxdiablostring literal,notsomestringtype that the standard does not provide.
C++doesprovide astd::stringtype but that's in the C++stringheader rather than the Cstring.h. In any case, it doesn't appear from theirweb presencethat CCS provides a C++ compiler, instead focusing on the C market.
|
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 put parentheses around the macro expansion.
```
#define B (A+1)
```
Then it will expand to
```
int foo = (100+1) * 10;
```
and you'll get the expected result.
|
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:
```
pair<int, int> generateUnPos() {
int occupied = 1;
int line, column;
while(occupied){
line = rand() % 4;
column = rand() %4;
if(board[line][column] == 0){
occupied = 0;
}
}
return make_pair(line, column);
}
```
I know it as something to do with structs but I can't figure it out. Can somebody help me out.
|
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 -pedanticunder GCC, can MSVC compile it?
|
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 a known-broken/intentionally-broken compiler does not seem like a worthwhile activity unless you actually have reason to want to use that compiler, rather than just allowing users of that compiler to link with your code.
|
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);
```
Loading this module on my Virtual Machine, I don't see my VM is halted.
Am I missing something?
|
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(read_list);
if (fileSize != 0) {
char line[256];
while (fgets(line, sizeof(line), read_list)) {
printf("%s", line);
}
}
```
|
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("Length of '%s' is %zu\n", myName, strlen(myName));
return 0;
}
```
Note the string in that code, it's a pointer to thepaxdiablostring literal,notsomestringtype that the standard does not provide.
C++doesprovide astd::stringtype but that's in the C++stringheader rather than the Cstring.h. In any case, it doesn't appear from theirweb presencethat CCS provides a C++ compiler, instead focusing on the C market.
|
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 put parentheses around the macro expansion.
```
#define B (A+1)
```
Then it will expand to
```
int foo = (100+1) * 10;
```
and you'll get the expected result.
|
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:
```
pair<int, int> generateUnPos() {
int occupied = 1;
int line, column;
while(occupied){
line = rand() % 4;
column = rand() %4;
if(board[line][column] == 0){
occupied = 0;
}
}
return make_pair(line, column);
}
```
I know it as something to do with structs but I can't figure it out. Can somebody help me out.
|
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 -pedanticunder GCC, can MSVC compile it?
|
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 a known-broken/intentionally-broken compiler does not seem like a worthwhile activity unless you actually have reason to want to use that compiler, rather than just allowing users of that compiler to link with your code.
|
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 to change the size of the text inwinbgi?
```
while(1)
{
settextstyle(DEFAULT_FONT, HORIZ_DIR, 4)
outtext(...)
settextstyle(DEFAULT_FONT, HORIZ_DIR, 2)
outtext(...)
}
```
|
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 it can never be greater then 255. In this case it will "wrap" to zero, so:
```
while(j != 0)
```
will work, or more simply and with no platform dependency issues, just change the type ofjtoint:
```
int j=1;
```
which makes much more sense.
|
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 anonimous memory will also do.
The output fromhugeadm --pool-list:
```
Size Minimum Current Maximum Default
2097152 1024 1024 1024 *
1073741824 0 0 0
```
The question is, how could I allocate memory, backed by huge pages?
|
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 to change the size of the text inwinbgi?
```
while(1)
{
settextstyle(DEFAULT_FONT, HORIZ_DIR, 4)
outtext(...)
settextstyle(DEFAULT_FONT, HORIZ_DIR, 2)
outtext(...)
}
```
|
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 it can never be greater then 255. In this case it will "wrap" to zero, so:
```
while(j != 0)
```
will work, or more simply and with no platform dependency issues, just change the type ofjtoint:
```
int j=1;
```
which makes much more sense.
|
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 anonimous memory will also do.
The output fromhugeadm --pool-list:
```
Size Minimum Current Maximum Default
2097152 1024 1024 1024 *
1073741824 0 0 0
```
The question is, how could I allocate memory, backed by huge pages?
|
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?. How much memory will be allocated in the first case at compile time?
|
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 an allocation on the stack.
|
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 536870912. Can anybody tell me what is wrong?
|
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);
printf("The entered number is %d",i);
getch();
}
```
I am able to run the above program in Turbo C++ but in Dev C++ I'm getting this error.
error:
|
<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 more portable solution, because<conio.h>will not work with GCC.
|
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 than you can avoid repeating thestructkeyword? I've heard that you should never use thetypedefvariant in C but nobody said why.
|
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 surrounding code does. For your own personal code do whatever you prefer.
|
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 expect it to, though the interface is a little clunky.
```
struct uint20_s {
unsigned int val : 20;
};
```
Broadly speaking it is non-trivial to implement integer semantics for word-sizes larger than those supported by the underlying hardware. There isan entire class of librariesdedicated to working with arbitrary precision numerics.
|
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?. How much memory will be allocated in the first case at compile time?
|
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 an allocation on the stack.
|
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 536870912. Can anybody tell me what is wrong?
|
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;
printf("6: %f\n", x/y);
printf("7: x = %f\n");
printf("8: %d\n", i/2);
printf("9: %f", x/2) ;
return 0;
}
```
In the execution phase, after the first outputprintf("1: %d\n", i);, I don't get anything in the terminal.
Any idea? (no compiling error)
|
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:
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.