question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago.
In C, why does
strtoul(argv[1])
j... |
Because you're calling it with the wrong number of arguments. Try
```
strtoul(argv[1], 0, 0);
```
Or if you want to enforce base-10 only:
```
strtoul(argv[1], 0, 10);
```
Be sure you included<stdlib.h>too!
|
I installed the gmp libraries in cygwin via its installer. I tried to compile a simple program with gcc.
```
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
int
main(void)
{
mpz_t test;
int i;
printf("enter number\n");
gmp_scanf("%Z",&test);
gmp_printf("test=%Z",test);
i=mpz_probab_... |
Are you asking gcc to link GMP?
i.e.:gcc -lgmp main.c ....
|
why should a code like this should provide a so high result when I give it the number 4293974227 (or higher)
```
int main (int argc, char *argv[])
{
unsigned long long int i;
unsigned long long int z = atoi(argv[1]);
unsigned long long int tmp1 = z;
unsigned long long int *numbers = malloc (sizeof (unsigned lon... |
atoi()returnsint. If you need larger numbers, trystrtol(),strtoll(), or their relatives.
|
Why does
```
char line[10] = "1234";
```
work fine but
```
char line[10];
line = "1234";
```
throws an
```
error: incompatible types in assignment
```
error?
|
Arrays are not pointers. In your second example,lineis a non-modifiable lvalue, but more importantly, no matter what you put on the righthand side, it can't have typechar [10](because arrays decay to pointers in non-lvalue context) and thus the types can never match.
For what it's worth, a string literal has typechar... |
I am trying to build my first Windows TUI Console app and i am facing some problems...Scanf nor fgets prevents user from entering unlimted characters unless hits enter etc..In a TUI interface thats a problem.. because it can get overwrite the line below...Is there any solution for this apart from getch
|
No, there isn't, at least not portably. C input is stream based, and doesn't have a concept of a keyboard. If you really want to write a text user interface, usencursesorpdcurses.
|
InCProgramming, We can enable/disable loop optimization using#pragmapreprocessor directive.
In which scenario,loop optimizationshould turned off ?
|
Optimisation is off by default when you compile for debug (so that source code lines in the debugger exactly match the code being executed).
You would only use the pragma in very specific circumstances, such as:
You find an optimisation limitation/bug leading to undefined behaviour (What Every C Programmer Should Kn... |
I have to write a simple program to output 16 bytes of data to a file at 0 and 48th position and have come up with this program:
```
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int f = create("test.tmp",774);
if(f>0)
{
write(f,"DEPARTMENT OF CS",16);
lseek(f... |
There's no function namedcreate
It's namedcreat
|
How can I update a GTK+ interface on a periodic event. For example, let's say I wanted to update a text field containing the time every 200 milliseconds. How is this typically done?
Update:
Another question (How one executes a periodic job in gtk application?) mentiones g_timeout_add. Is this the best way to go ab... |
This tutorialhas an example. (Search for the section titled "A timer example".)
The short answer is "useg_timeout_add".
|
I want to check whether an allocated memory is aligned or not. I am using_aligned_malloc(size, align);And it returns a pointer. Can I check it by simply dividing the pointer content by 16 for example? If the the pointer content is divisible by 16, does it mean that the memory is aligned by 16 bytes?
|
An "aligned" pointer by definition means that the numeric value of the pointer is evenly divisible by N (where N is the desired alignment). To check this, cast the pointer to an integer of suitable size, take the modulus N, and check whether the result is zero. In code:
```
bool is_aligned(void *p, int N)
{
retur... |
Can we say that "C language operators are polymorphic" ?
For example if
```
int a, b;
float p, q;
a+b;
a+p;
p+q;
```
etc will generate different code when assembled, as the type conversion is needed the floating point coprocessor instruction needs to be executed to make the conversion and the floating point additi... |
Yes, in theory this could be called static polymorphism or operator overloading. But since the polymorphism is fixed in its range of applicable types by the language definition, it's not a very interesting polymorphism.
|
I use ANSI C89 (not C++), and I want to generateNaN,-Infinityand+Infinity.
Is there any standard way (eg. standard macro)?
Or is there any platform and compiler independent way to generate these numbers?
```
float f = 0.0 / 0.0; // Is f ALWAYS in any platform is NaN?
```
|
There is in C99, but not in previous standards AFAIK.
In C99, you'll haveNANandINFINITYmacros.
From"Mathematics<math.h>"(§7.12) section
The macroINFINITYexpands to a constant expression of type float representing positive or unsigned infinity, if available; ...
If you're stuck with ANSI C89, you're out of luck. See... |
The code:
```
int main(void)
{
printf("pid: %d\n", getpid());
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork Failed!");
exit(-1);
} else if (pid == 0) {
execv("sum", argv);
} else {
printf(" pid: %d\n", pid);
wait(NULL);
}
}
```
The output:
```... |
```
RETURN VALUE
On success, the PID of the child process is returned in the parent,
and 0 is returned in the child. On failure, -1 is returned in the parent,
no child process is created, and errno is set appropriately.
```
So, in the parent process, fork() returns the pid of the child pr... |
I have been using the GCC Compiler for months, which is great, and works very well. But I wonder which C++ Compiler do big/medium enterprises use for high optimizations/performance in Linux (x86, PowerPC...).
It may seem a very stupid question, but I havent found the answer anywhere.
As far as I know, the best Power... |
In the places I have worked we have always used gcc, even for embedded applications/software.
Performance improvements are much more likely to come from your code rather than your compiler choice anyway!
|
I want to convert an 32-bit ASCII number (e.g. "FE257469") to the equivalent 32-bit hex number which will be stored on a 32-bit variable. Most importnatly, I want to do thatwithoutusing any library function like sscanf(), atoi(), etc.
Any ideas on that?
Thank in advance.
|
Here is an implementation of such a function based on a switch:
```
unsigned int parseHex( char *str )
{
unsigned int value = 0;
for(;; ++str ) switch( *str )
{
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
value = value <<... |
I have this string
```
c1eb044f0708015b267913fc4dff5aabe3dd4a97f10f7ba935cd360000000000
```
How does one swap it so it becomes
```
000000000036cd35a97b0ff1974adde3ab5aff4dfc1379265b0108074f04ebc1
```
Those two are basically examples, but that is what i need to do, but not know how as i have very little knowledge o... |
```
for (int i = 0; i < size; i += 2) {
myNewStr[size - i - 2] = myStr[i];
myNewStr[size - i - 1] = myStr[i + 1];
}
```
|
I have a question about program exit state in Linux. In my program, I fork a child process and invokewaitpidto reap it. Whenwaitpidreturns, I wanna check exit state of my child process. I turn to manual for help and find that the second argument ofwaitpidwill hold exit state and I can use macroWEXITSTATEto read it. Ho... |
I think you will find that0x377is really, or should have been,0377.
It's octal, so3778is 8 bits.
|
Fromhttp://www.adp-gmbh.ch/cpp/gcc/create_lib.html:
Note: the library must start with the three lettersliband have the suffix.a.
Is this an operating system convention, or agcc/arquirk? Xcode seems to be able to create libraries without the prefix. What's it doing differently?
|
You can name a library whatever you want, but if you want gcc's-lflag to find the right one, you need to name it the way that link describes. For example:
```
gcc -o myapp myapp.c -lm
```
Will compilemyapp.c, link the resulting object withlibm.a, and output an executable calledmyapp. These days, there might be a ... |
select(2) (amongst other things) tells me whether I can write to a fd of a file without blocking. However, does it guarentee me that I can write a full 4096 bytes without blocking?
NoteI am interested in normal files on disk. Not sockets or the like.
In other words: doesselectsignal when we can just write one sing... |
Wheneverselect()indicates that your file is ready, you can try writing N bytes, for any N>0.write()will return the number of bytes actually written. If it equals N, you can write again. If it's less than N, then the next write will block.
NoteNormal files on disk don't block. Sockets, pipes and terminals do.
|
```
#include <stdio.h>
int main()
{
int i = 10;
printf("%d\n", ++(-i)); // <-- Error Here
}
```
What is wrong with++(-i)? Please clarify.
|
-igenerates a temporary and you can't apply++on a temporary(generated as a result of an rvalue expression). Pre increment++requires its operand to be an lvalue,-iisn't an lvalue so you get the error.
|
I was trying some C++, but I'm too new to this and you can say that this is my first day at C++. So I was trying to create a function but I was stuck with arrays! When I create a Character based array like this :
```
char x[7][7] = {"sec","min","hr","day","week","month","year"};
```
And when I try to fetch the data ... |
Since you have 7 values, and the array is indexed from 0, you only need to count up to 6, not 7. Modify yourforloop asfor (i=0;i < 7;i++). (<instead of<=.)
You're going over the end of the array, which may give you garbage data or may just crash your program.
|
In3["XoePhoenix"], array index is of type array of characters. Can we do this in C? Isn't it true that an array index must be an integer?
What does3["XeoPhoenix"]mean?
|
3["XoePhoenix"]is the same as"XoePhoenix"[3], so it will evaluate to the char'P'.
The array syntax in C is not more than a different way of writing*( x + y ), wherexandyare the sub expressions before and inside the brackets. Due to the commutativity of the addition these sub expressions can be exchanged without chang... |
i am creating file system filter driver and need to open some files to check attributes in dispatch routines. I am using ZwCreateFile(). But my dispatch routines is called at every file system request, so my ZwCreateFile() will then call again my dispatch routine. What is the best method to not enter deadlock? I think... |
TryIoCreateFileSpecifyDeviceObjectHint,IoCreateFileExorFtlCreateFile.
|
In static linking, how does the linker knows which library file to link the user's compiled object code against? I mean the header only contains the function protoytpes that may be used in the source code, not the library file name.. isn't it?
|
That's why you provide the linker with a list of libraries to link against!
e.g. for GCC, you might do something like:
```
gcc my_prog.o -lm -lpthread -o my_prog
```
Here, the-lflag is used to tell the linker to link againstlibmandlibpthread.
|
I'm writing code for a primality testing function that handles long long int's.Do I have to use special operators for such large numbers?Is there any documentation concerning large number manipulation in C?I'm using the gnu standard library.Thanks.
|
No, you don't need to do anything special. You handle along long intjust the same way as you would handle aint. Just beware of overflows, as with every native integer type.
|
I need to create several id's for several structs.
Now I want that each id will start from 00001 to 99999
for example:
the id of the first struct is 00001the id of the second struct is 00002...and so on...
Now I need toscanfit, and thenprintfit so the id that shown in the black window will look like this:The id of ... |
For a numerical variable, there is no concept of "leading zeroes". So if you want to use "0001" in your code, you will have to convert it into a string, adding leading 0's as required.
|
I have this string
```
c1eb044f0708015b267913fc4dff5aabe3dd4a97f10f7ba935cd360000000000
```
How does one swap it so it becomes
```
000000000036cd35a97b0ff1974adde3ab5aff4dfc1379265b0108074f04ebc1
```
Those two are basically examples, but that is what i need to do, but not know how as i have very little knowledge o... |
```
for (int i = 0; i < size; i += 2) {
myNewStr[size - i - 2] = myStr[i];
myNewStr[size - i - 1] = myStr[i + 1];
}
```
|
I have a question about program exit state in Linux. In my program, I fork a child process and invokewaitpidto reap it. Whenwaitpidreturns, I wanna check exit state of my child process. I turn to manual for help and find that the second argument ofwaitpidwill hold exit state and I can use macroWEXITSTATEto read it. Ho... |
I think you will find that0x377is really, or should have been,0377.
It's octal, so3778is 8 bits.
|
Fromhttp://www.adp-gmbh.ch/cpp/gcc/create_lib.html:
Note: the library must start with the three lettersliband have the suffix.a.
Is this an operating system convention, or agcc/arquirk? Xcode seems to be able to create libraries without the prefix. What's it doing differently?
|
You can name a library whatever you want, but if you want gcc's-lflag to find the right one, you need to name it the way that link describes. For example:
```
gcc -o myapp myapp.c -lm
```
Will compilemyapp.c, link the resulting object withlibm.a, and output an executable calledmyapp. These days, there might be a ... |
select(2) (amongst other things) tells me whether I can write to a fd of a file without blocking. However, does it guarentee me that I can write a full 4096 bytes without blocking?
NoteI am interested in normal files on disk. Not sockets or the like.
In other words: doesselectsignal when we can just write one sing... |
Wheneverselect()indicates that your file is ready, you can try writing N bytes, for any N>0.write()will return the number of bytes actually written. If it equals N, you can write again. If it's less than N, then the next write will block.
NoteNormal files on disk don't block. Sockets, pipes and terminals do.
|
```
#include <stdio.h>
int main()
{
int i = 10;
printf("%d\n", ++(-i)); // <-- Error Here
}
```
What is wrong with++(-i)? Please clarify.
|
-igenerates a temporary and you can't apply++on a temporary(generated as a result of an rvalue expression). Pre increment++requires its operand to be an lvalue,-iisn't an lvalue so you get the error.
|
I was trying some C++, but I'm too new to this and you can say that this is my first day at C++. So I was trying to create a function but I was stuck with arrays! When I create a Character based array like this :
```
char x[7][7] = {"sec","min","hr","day","week","month","year"};
```
And when I try to fetch the data ... |
Since you have 7 values, and the array is indexed from 0, you only need to count up to 6, not 7. Modify yourforloop asfor (i=0;i < 7;i++). (<instead of<=.)
You're going over the end of the array, which may give you garbage data or may just crash your program.
|
In3["XoePhoenix"], array index is of type array of characters. Can we do this in C? Isn't it true that an array index must be an integer?
What does3["XeoPhoenix"]mean?
|
3["XoePhoenix"]is the same as"XoePhoenix"[3], so it will evaluate to the char'P'.
The array syntax in C is not more than a different way of writing*( x + y ), wherexandyare the sub expressions before and inside the brackets. Due to the commutativity of the addition these sub expressions can be exchanged without chang... |
i am creating file system filter driver and need to open some files to check attributes in dispatch routines. I am using ZwCreateFile(). But my dispatch routines is called at every file system request, so my ZwCreateFile() will then call again my dispatch routine. What is the best method to not enter deadlock? I think... |
TryIoCreateFileSpecifyDeviceObjectHint,IoCreateFileExorFtlCreateFile.
|
In static linking, how does the linker knows which library file to link the user's compiled object code against? I mean the header only contains the function protoytpes that may be used in the source code, not the library file name.. isn't it?
|
That's why you provide the linker with a list of libraries to link against!
e.g. for GCC, you might do something like:
```
gcc my_prog.o -lm -lpthread -o my_prog
```
Here, the-lflag is used to tell the linker to link againstlibmandlibpthread.
|
I'm writing code for a primality testing function that handles long long int's.Do I have to use special operators for such large numbers?Is there any documentation concerning large number manipulation in C?I'm using the gnu standard library.Thanks.
|
No, you don't need to do anything special. You handle along long intjust the same way as you would handle aint. Just beware of overflows, as with every native integer type.
|
I need to create several id's for several structs.
Now I want that each id will start from 00001 to 99999
for example:
the id of the first struct is 00001the id of the second struct is 00002...and so on...
Now I need toscanfit, and thenprintfit so the id that shown in the black window will look like this:The id of ... |
For a numerical variable, there is no concept of "leading zeroes". So if you want to use "0001" in your code, you will have to convert it into a string, adding leading 0's as required.
|
What would be the output of this program ?
```
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int x=20,y=30,z=10;
int i=x<y<z;
printf("%d",i);
getch();
}
```
Actuallyi=20<30<10, so the condition is false and the value ofishould be 0 butiequals 1. Why?
|
Thisint i=x<y<z;doesn't work the way you intended.
The effect isint i=(x<y)<z;, wherex<yis evaluated first, and the valuetrueis then compared toz.
Pascal points out below that in C the result of the comparison is1instead oftrue. However, the C++trueis implicitly converted to1in the next comparison, so the result i... |
I don't want to resize the entire image structure, but the images I am working with are too large to easily view with cvShowImage. Is there a way to resize their view within the window created by cvShowImage?
|
No there isn't, you will have to create a new image structure and use cvResize.
|
can i use curl's functions to receive clients https connections? i want to write server using libcurl, should i use naked sockets to accept connections? Oficial documentation provides following example:
```
/* read the response */
for(;;)
{
char buf[1024];
wait_on_socket(sockfd, 1, 60000L);
res = curl_easy_re... |
FromLIBCURL - about
libcurl is a free, open source client to get documents/files from servers, using any of the supported protocols.
It is aclientlibrary not an HTTPS server.
|
this is probably an essentially trivial thing, but it somewhat escapes me, thus far..
char * a3[2];a3[0] = "abc";a3[1] = "def";char ** p;p = a3;
this works:
printf("%p - \"%s\"\n", p, *(++p));
this does not:
printf("%p - \"%s\"\n", a3, *(++a3));
the error i'm getting at compilation is:
lvalue required as increm... |
a3 is a constant pointer, you can not increment it. "p" however is a generic pointer to the start of a3 which can be incremented.
|
Is there any method inCcan find a text within another text?
For example,text = "abaHello",textneedtoSearch = "Hello";.
If thetextcontains"Hello",return true, else return false.
|
Usestrstr, seehttp://pubs.opengroup.org/onlinepubs/9699919799/functions/strstr.html
|
I am trying to parse Photoshop PSD files and I want to extract layer information, including text.
Is there any API in Objective-C that can help me to extract this information from PSD files?
|
There is no framework or 3rd party parser available for parsing the PSD file in Objective-C
But there is one available in C language, Which you could use with your objective-C code
Forum Source:
Is there a PSD file parser for Objective-C? I want to replace a layer image and output the result as an NSImage.
load la... |
I have C/Java knowledge but i never understand yet, how some hardwares show there own screens/graphics from poweron stage to user interface (where it never shows linux/unix boot screen nor it shows windows booting screens).
My question is, Compared to VCR/TV digicoders poweron till user interfaces, how its made? Do w... |
Many embedded systems useu-bootas a boot loader. U-boot provides the ability to display a"splash" screenwhile the linux kernel is booting.
|
Do different threads within a single process have distinct independent file descriptor tables? If multiple threads within the same process concurrently access a single file, will the offset into the file for two different calls toopenperformed by different threads be thread-specific?
|
No, there is only one file descriptor table per process, and it's shared among all the threads.
From your problem description, you might want to look into the pread() and pwrite() functions.
|
Is there a secure alternative tomkdir()for C? I am examining some code and notice it is using calls tomkdir(). From what I have read on the US-CERT Secure Coding site, use of that function leaves it vulnerable to "Time of Check, Time of Use" (TOCTOU).
Edit
From the miniunz.c source for zlib
```
int mymkdir(dirname)... |
Your question is a little vague; a reference to the US-CERT document and some sample code would be nice.
Nevertheless, I bet the answer ismkdirat().
|
I want to write a program (create an exe file) to uninstall a program in WM 5.0. I was searching in Google but nothing really show a step by step how to do this. I had a step by step instruction on how to install a cab file programmatically, but I can't find something similar to unistall the program. I have seen so... |
Try to readthisarticle. If I understood correctly what you need is to pass configuration xml toProcessConfigurationmethod.
I hope it helps.
|
In WinAPI is there a mouse move notification for the full desktop (full screen) and not for a window only?
I would like to receive mouse screen coordinates in my main window procedure.
Edit:
What I try to do is getting the coordinates from the mouse when dragging from a button in my window to outside that window.
|
Not as such, no. If you wanted to do something anywhere on the desktop from within your program, e.g. point somewhere or draw something anywhere, you could capture the mouse and then follow the movement until the mouse button is released. SeeSetCapturefor this.
For an example, see this article on MSDN:Drawing Lines w... |
Compilers these days tend to do a significant amount of optimizations. Do they also remove unused functions from the final output?
|
It depends on the compiler. Visual C++ 9 can do that - unusedstaticfunctions are removed at compilation phase (there's even aC4505 warningfor that), unused functions with external linkage can be removed at link phasedepending on linker settings.
|
i need to add some files to results returned by FindFirstFile and FindNextFile under windows. Is this possible by file system filter driver or what type of drivers?
Thank you
|
You can do this by File System Filter Driver. But you can do this by implementing a system wide API hook. I have not tried it before but you really don't need to take the pains of writing the drivers and making the system unstable in case of spoiling the driver stack.
System Wide API Hooking
API Hooking Revealed
|
I have to do a sign extension for a 16-bit integer and for some reason, it seems not to be working properly. Could anyone please tell me where the bug is in the code? I've been working on it for hours.
```
int signExtension(int instr) {
int value = (0x0000FFFF & instr);
int mask = 0x00008000;
int sign = (... |
Why is wrong with:
```
int16_t s = -890;
int32_t i = s; //this does the job, doesn't it?
```
|
Is callingpthread_exitexplicitly from the thread routine required?
Example code:
```
pthread_create(&pth, NULL, (void *)func, parg);
... func() {
...
//do I have to call pthread_exit() here?
return 0;
}
```
|
Thepthread_createdocumentation says:
If the start_routine returns, the effect is as if there was an implicit call to pthread_exit() using the return value of start_routine as the exit status.
So no, no need to call it explicitly.
|
I have a server application with a listening socket opened on a specific IP port.
How can I allow the socket to enable incoming connections from just one specified IP address?
|
You'll have to either use some firewall software to restrict incoming requests to that port, or shut down accepted connections that you do not want to service (based on the socket address returned byaccept).
There might be libraries out there that do that for you, but the socket API doesn't have anything to do it aut... |
I try to get product of two matrix say A and B into C using cblas provided by intel MKL.
Is there any reason for this to be result in error?
```
double * A, *B, *C;
A = (double *) calloc(20 * 200, sizeof (double));
B = (double *) calloc(200 * 200, sizeof (double));
C = (double *) calloc(20 * 200, sizeof (double));
... |
Double check all the parameters to cblas_dgemm. If you have a mistake, the function could be reading beyond the bounds of the array. For small sizes that won't trigger a fault, since the bad addresses will still fall inside a single memory page. (But the math will be wrong, you should check it.) But a 200x200 matrix i... |
I'm trying validate an X.509 certificate received over a network. I have understood that the digital signature is created by creating a message digest of the fields(don't know which fields) in the signature and then encrypting it using the CA(Certificate Authority) private Key.We can validate the certificate by decryp... |
From a glance atthe RFCit appears to be the wholetbsCertificatefield.
[...] a digital signature computed upon
the ASN.1 DER encoded tbsCertificate. The ASN.1 DER encoded
tbsCertificate is used as the input to the signature function.
|
I recently wrote a small C code which uses sockets to listen on a port. It simply echos back the request made to it by a browser. It creates a thread for daemon process and also for servicing new requests. I am doing it simply to learn more about webservers in general. I wanted to know what to do ahead?
I was plannin... |
Thisis a really good book on HTTP. I recommend getting started with that then maybe the relevant RFC's. Also maybe check out the source oflibcurl, a c library for http, https, ftp etc. Hope this helps :)
AlsoTiny HTTPdis a small http server someone wrote for a school project, you can learn a lot from the source from ... |
we use One-Time initialization for pthreads like this:
```
/* define a statically initialized pthread_once_t variable */
pthread_once_t once_var = PTHREAD_ONCE_INIT;
/* we call pthread_once function in threads */
int pthread_once(pthread_once_t *once_control, void (*init)(void));
```
when more than one thread is go... |
No, you don't need a mutex for this. Thepthread_oncecall (link here) is guaranteed to be executed once and once only, even if multiple threads try it at the same time.
It's theonce_varthat's protecting the call from being executed more than once. It will work as expected, provided that you:
initialise theonce_vartoP... |
Does there exist a way to allocate some memory and have some sort of callback (be it pointer to a function or signal) when the memory is being accessed (either read or written to)?
For example, if I said allocate 1mb of memory, I would like to have a way to call a function when any of that 1mb is being accessed.
The... |
Yes, there is.
Use the mprotect(2) system call (see:http://linux.die.net/man/2/mprotect) to set read only or no access memory protection on the page and set a SIGEGVsignal handler that will be called when the memory has been accessed.
Note that you will need to use mprotect in your signal handler to actually allow t... |
```
struct tm *localtime(const time_t *timep);
```
I checkedman localtimebut there's no words on whether it's my duty to clean it after using.
And in fact I have many similar doubts on functions returning a pointer, how do you determine it should be freed or not ?
|
This information should be in the man page - mylocaltimeman page says:
The return value points to a
statically allocated struct...
Statically allocated objects should not be passed tofree(), so this is your answer - no, you shouldnotfree the return value oflocaltime().
The only way to tell in the general case is ... |
```
#if (NGX_SOLARIS)
ngx_int_t i;
size_t size;
#endif
```
I know thatNGX_SOLARISis finally determined when we run./configure,but how are these macros actually defined,can you provide a detailed example that demonstrates how most./configureworks?
|
./configureruns through all the checks for what your system's platform is, what capabilities your compiler has, etc. and then it usesautomaketo generate Makefiles with stuff likeCPPFLAGSwhich define the macros it needs to pass to the preprocessor during compilation.
This is all part of the GNU build system:http://dev... |
```
(gdb) p (char*)0x7fffffffe9c8
$16 = 0x7fffffffe9c8 "\363\353\377\377\377\177"
```
It doesn't look like ascii nor multibyte,what's that?
|
These areoctalcharacter escapes. They are usually used to insert bytes into a string that don't have a meaning as text or need to have a certain binary value.\377for instance is the hexadecimal valueffor decimal255which would be thisÿin ASCII but most likely has a very different meaning in this context.
|
I have a server application with a listening socket opened on a specific IP port.
How can I allow the socket to enable incoming connections from just one specified IP address?
|
You'll have to either use some firewall software to restrict incoming requests to that port, or shut down accepted connections that you do not want to service (based on the socket address returned byaccept).
There might be libraries out there that do that for you, but the socket API doesn't have anything to do it aut... |
I try to get product of two matrix say A and B into C using cblas provided by intel MKL.
Is there any reason for this to be result in error?
```
double * A, *B, *C;
A = (double *) calloc(20 * 200, sizeof (double));
B = (double *) calloc(200 * 200, sizeof (double));
C = (double *) calloc(20 * 200, sizeof (double));
... |
Double check all the parameters to cblas_dgemm. If you have a mistake, the function could be reading beyond the bounds of the array. For small sizes that won't trigger a fault, since the bad addresses will still fall inside a single memory page. (But the math will be wrong, you should check it.) But a 200x200 matrix i... |
I'm trying validate an X.509 certificate received over a network. I have understood that the digital signature is created by creating a message digest of the fields(don't know which fields) in the signature and then encrypting it using the CA(Certificate Authority) private Key.We can validate the certificate by decryp... |
From a glance atthe RFCit appears to be the wholetbsCertificatefield.
[...] a digital signature computed upon
the ASN.1 DER encoded tbsCertificate. The ASN.1 DER encoded
tbsCertificate is used as the input to the signature function.
|
I recently wrote a small C code which uses sockets to listen on a port. It simply echos back the request made to it by a browser. It creates a thread for daemon process and also for servicing new requests. I am doing it simply to learn more about webservers in general. I wanted to know what to do ahead?
I was plannin... |
Thisis a really good book on HTTP. I recommend getting started with that then maybe the relevant RFC's. Also maybe check out the source oflibcurl, a c library for http, https, ftp etc. Hope this helps :)
AlsoTiny HTTPdis a small http server someone wrote for a school project, you can learn a lot from the source from ... |
we use One-Time initialization for pthreads like this:
```
/* define a statically initialized pthread_once_t variable */
pthread_once_t once_var = PTHREAD_ONCE_INIT;
/* we call pthread_once function in threads */
int pthread_once(pthread_once_t *once_control, void (*init)(void));
```
when more than one thread is go... |
No, you don't need a mutex for this. Thepthread_oncecall (link here) is guaranteed to be executed once and once only, even if multiple threads try it at the same time.
It's theonce_varthat's protecting the call from being executed more than once. It will work as expected, provided that you:
initialise theonce_vartoP... |
Does there exist a way to allocate some memory and have some sort of callback (be it pointer to a function or signal) when the memory is being accessed (either read or written to)?
For example, if I said allocate 1mb of memory, I would like to have a way to call a function when any of that 1mb is being accessed.
The... |
Yes, there is.
Use the mprotect(2) system call (see:http://linux.die.net/man/2/mprotect) to set read only or no access memory protection on the page and set a SIGEGVsignal handler that will be called when the memory has been accessed.
Note that you will need to use mprotect in your signal handler to actually allow t... |
```
struct tm *localtime(const time_t *timep);
```
I checkedman localtimebut there's no words on whether it's my duty to clean it after using.
And in fact I have many similar doubts on functions returning a pointer, how do you determine it should be freed or not ?
|
This information should be in the man page - mylocaltimeman page says:
The return value points to a
statically allocated struct...
Statically allocated objects should not be passed tofree(), so this is your answer - no, you shouldnotfree the return value oflocaltime().
The only way to tell in the general case is ... |
```
#if (NGX_SOLARIS)
ngx_int_t i;
size_t size;
#endif
```
I know thatNGX_SOLARISis finally determined when we run./configure,but how are these macros actually defined,can you provide a detailed example that demonstrates how most./configureworks?
|
./configureruns through all the checks for what your system's platform is, what capabilities your compiler has, etc. and then it usesautomaketo generate Makefiles with stuff likeCPPFLAGSwhich define the macros it needs to pass to the preprocessor during compilation.
This is all part of the GNU build system:http://dev... |
```
(gdb) p (char*)0x7fffffffe9c8
$16 = 0x7fffffffe9c8 "\363\353\377\377\377\177"
```
It doesn't look like ascii nor multibyte,what's that?
|
These areoctalcharacter escapes. They are usually used to insert bytes into a string that don't have a meaning as text or need to have a certain binary value.\377for instance is the hexadecimal valueffor decimal255which would be thisÿin ASCII but most likely has a very different meaning in this context.
|
Is it possible to declare an array of pointers and later on initialize either of them and assign a value, in aCheader file?
```
char *i[2];
i[0] = "abc";
```
the following does not work.
```
char *x = "def"; // this will, of course.
```
How am I supposed to declare and assign values for an array of pointers?
|
This has nothing to do with header files. You cannot create a .c file and put in it code like this:
```
char *i[2];
i[0] = "abc";
```
In C, all code except definitions and initialisations must be inside functions, and your second statement is neither of these - it is an assignment.
An initialisation for your arra... |
In C, how can I copy a string with begin and end indices, so that the string will only be partially copied (from begin index to end index)?
This would be like 'C string copy'strcpy, but with a begin and an end index.
|
Usestrncpy
e.g.
```
strncpy(dest, src + beginIndex, endIndex - beginIndex);
```
This assumes you've
Validated thatdestis large enough.endIndexis greater thanbeginIndexbeginIndexis less thanstrlen(src)endIndexis less thanstrlen(src)
|
consider the following two code:
```
void PrintLetter(char *src)
{
while(*src != '\0')
{
printf("%c",*src);
src++;
}
}
```
and
```
void PrintLetter(char *src)
{
int i;
for(i=0;src[i];i++)
printf("%c",src[i]);
}
```
Is there any performance difference between the two?
|
None whatsoever. The compiler will perform its optimizations regardless of the form you are writing. The underlying assembly code is the same.
|
I was reviewing some code and I saw someone do a
```
if (0 == strcmp(foo,""))
```
I am curious because I think it would be faster to do a
```
if (foo[0] == '\0')
```
Is this correct or is strcmp optimized enough to make them the same.
(I realize that even if there was some difference it would be small, but am thi... |
You're right: since callingstrcmp()adds up the stack management and the memory jump to the actual strcmp instructions, you'll gain a few instructions by just checking the first byte of your string.
For your curiosity, you can check the strcmp() code here:http://sourceware.org/git/?p=glibc.git;a=blob;f=string/strcmp.c... |
The two declarations are as follows:
```
int (*p)[8];
int *p[8];
```
|
The first is asinglepointer to an array of 8 integers, while the second is anarrayof 8 pointers, each to an integer.
If you just kick upcdecl, it's wonderful for this sort of thing:
```
pax$ cdecl
Type `help' or `?' for help
cdecl> explain int (*p)[8];
declare p as pointer to array 8 of int
cdecl> explain int *p[8... |
sorry i modified the code now:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
int i=0;
char** f=NULL;
char* ff=NULL;
ff="abcd";
f=( char**)malloc ((i + 1) * sizeof (char *)+5);
f[0]=ff;
// strcpy(f[0],ff); (this again giving same error)
strncat(f[0... |
you are setting f<-ffff points to the start of a constant char[] ("abcd")
and then you change the value of *f (which is exactly *ff) thus - access violation.
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago.
```
int i = 1;
while (i < n/2)
{
... |
O(n):outer loop runslogntimes, in each iteration: i=1,2,4,8,...n/4 (entrance values)inner loops runs2*itimes (entrance values)so at overall you get:2+4+8+...+n/2 = n-2 = O(n)
|
After callingfork, the current process will callexit(0).
But the child will continue.
```
switch(fork())
{
case -1:
exit(1);
case 0:
// child process continues
break;
default:
// the current process exits
exit(0);
}
```
How can I continue debugging the child process in this case?
|
Look atthis. Use:
```
set follow-fork-mode <mode>
```
Set the debugger response to a program call of fork or vfork. A call to fork or vfork creates a new process. The<mode>argument can be:
parent: The original process is debugged after a fork. The child process runs unimpeded. This is the default.
child: The new p... |
```
umask(0);
fd = open("/dev/null", O_RDWR);
```
Here'sman 2 umask:
```
umask() sets the calling process’s file mode creation mask (umask) to mask & 0777.
```
But it doesn't make sense for me,as when we callopen,we will also provide a mode parameter.
So what's the point ofumask?
|
The umask is applied to all modes used in file system operations. From the manualopen(2):
The permissions of the created file are(mode & ~umask)
So with a single call to umask, you can influence the mode of all create files.
This is usually used when a program wants the user to allow to overrule the default g... |
```
ngx_int_t ngx_daemon(ngx_log_t *log)
{
int fd;
switch (fork()) {
case -1:
ngx_log_error(NGX_LOG_EMERG, log, ngx_errno, "fork() failed");
return NGX_ERROR;
case 0:
break;
default:
exit(0);
}
```
It seems pointless to me,as it only changes the pid,nothing ... |
The process becomes detached from the terminal so that when the user that started it quits his session, the process remains running.
Daemonizing is not only about the fork, it involves callingsetsid(2)in the child process that detaches the process from the controlling terminal. If you runpsyou can see such processes ... |
I would be interested in answers for both Linux and NT (or any other for that matter)
Edit:
Thanks Laurion for the answer.
More information here:
http://www.symantec.com/connect/articles/dynamic-linking-linux-and-windows-part-onehttp://www.symantec.com/connect/articles/dynamic-linking-linux-and-windows-part-two
|
The runtime loader normally fixes up references to imported functions when the module is loaded. It looks at the table of imported functions and puts in the proper address. The module uses the imported functions through an indirection table.
|
I'm learning C/C++ right now and I am reading about file operations. Suppose a program A is working with an external file (say, a text file) and another another program B is, say, trying to move the file (or worse, delete it). Is it possible to tell the OS to inform the program B that the file is in use, even though i... |
What you're trying to do is calledfile locking. Search for "file locking in C".
|
How can I get the address of a multidimensional static array?
For example, this is my array
```
char array[2][10] = {"word1", "word2"};
```
Is it possible to get the address to make me reference this array using a pointer like this?
```
char** pointer;
```
I tried &array or directly pointer = (char**)array; but it... |
char **pointermeans that a pointer is pointing to a pointer.
So*pointeris expected to be a pointer (e.g. 4-byte value which can be interpreted as an address).
This is not the case with your array: it is a contiguous area in memory (20 bytes).
So when you try to convert the array tochar **your application crashes.
It... |
Im writing timers manager in C, which involves:
creating new timerremoving timersremoving dead timerfreezing timersand all the other stuff which i did not yet think about.
The key is - amount of memory should be as small as possible.
At first i thought about linked list, but if i remove some of the middle part, i sh... |
You don't need to rebuild anything when removing from a linked list. It's anO(1)op. No matter what structure you'll choose you'll probably have to be careful about pointers.
|
I'm very new to C. I want to add two one dimensional integer array namea[10] b[10].
I want to put the result in a 2dimentional arrayc[5][2]like
```
c[i][j] = a[i]+b[i];
```
But if I use 2forloops then how can I accessa[9],b[9]value. So I want to use a singleforloop which performa[i]+b[i]and puts the result inc[i][j]... |
if i undersood your problem, you can do this:
```
int col=0; //col counter
int row=0; // row counter
for(int x=0;x<9;x++)
{
if(col>x/2) // check the end of row
{
row++; // increment row
col=0; // reset col counter
}
c[row][col]=a[x]+b[x]; // assignement
col++;
}
```
|
I have been asked in an interview why there is a need of calculating the size of the address to which it is bound in bind system call.
```
bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr))
```
Means i would like to know what is purpose of having third argument in bind system call??
|
Because thesockaddrstructure serves more or less as a "base" structure for "derived" structures likesockaddr_in. It'salmostan inheritance mechanism.
sockaddrcontains variable-length data that can be used by "derived" structures likesockaddr_*, hence you need to precise the effective size of the "derived" structure.
|
I have 2 variables:
```
int a;
char b[10];
```
I want to combine/append both data in one array:
```
temp[50];
```
How can I do that?
|
You didn't give us enough information about the type of temp or why you want to do that, generally it doens't make much sense to combine types. However if temp is a char array and you want to concatenate both of them for some kind of useful output, you can use sprintf:
```
int a = 10;
char b[10] = "apple";
char temp[... |
I have grown accustomed tostrtodand variants.
I am wondering why there is nostrtoishipped with<stdlib.h>.
Why is it that the integer type is left out of this party?
Specifically I am asking why there is not a version ofatoiwith the safety features ofstrtod?
|
strtol()converts a string to an integer, a long integer but an integer nevertheless. There isatoi()but it should be avoided in most cases due to the fact that it lacks a mechanism for error reporting from invalid input.
|
I've just written a function that returns a pointer to a block of memory allocated by malloc. If I call free() on the returned pointer, will this free the memory?
I tried reading up on this, but I can't find anything that says whether you can call a different pointer pointing to the same location and whether that wi... |
Yes callingfreewill free the memory. Its not the pointer that get freed but the memory that the pointer points to that is freed.
|
I am wondering how to implement a bubble sort on a singly-linked list. Let's say for example that we have list that consists of following nodes:
```
struct node {
int value;
struct node* next;
}
```
I believe that there are 2 ways to acomplish this:
```
1)to directly exchange `values` in memory
2)to change `n... |
Your values are very small, so I expect exchanging them to be more efficient than changing the pointer structure. As always, you will have to measure the actual performance in your use case to be sure.
|
So I'm having trouble getting even a simple Makefile to work. Heres what I have:
```
proj : driver.o
icc -g -O3 -openmp driver.o -o proj
driver.o : driver.c driver.h
icc -g -O3 -openmp driver.c
```
I feel like it's pretty straight forward. Proj only depends on driver.o which in turn depends on driver.c and d... |
You should giveicca-I.option to get it to look for include files in the current directory.
```
icc -I. -c -g -O3 -openmp driver.c
```
(I took the liberty of also adding the-cflag to prevent linking.)
|
I have 2 variables:
```
int a;
char b[10];
```
I want to combine/append both data in one array:
```
temp[50];
```
How can I do that?
|
You didn't give us enough information about the type of temp or why you want to do that, generally it doens't make much sense to combine types. However if temp is a char array and you want to concatenate both of them for some kind of useful output, you can use sprintf:
```
int a = 10;
char b[10] = "apple";
char temp[... |
I have grown accustomed tostrtodand variants.
I am wondering why there is nostrtoishipped with<stdlib.h>.
Why is it that the integer type is left out of this party?
Specifically I am asking why there is not a version ofatoiwith the safety features ofstrtod?
|
strtol()converts a string to an integer, a long integer but an integer nevertheless. There isatoi()but it should be avoided in most cases due to the fact that it lacks a mechanism for error reporting from invalid input.
|
I've just written a function that returns a pointer to a block of memory allocated by malloc. If I call free() on the returned pointer, will this free the memory?
I tried reading up on this, but I can't find anything that says whether you can call a different pointer pointing to the same location and whether that wi... |
Yes callingfreewill free the memory. Its not the pointer that get freed but the memory that the pointer points to that is freed.
|
I am wondering how to implement a bubble sort on a singly-linked list. Let's say for example that we have list that consists of following nodes:
```
struct node {
int value;
struct node* next;
}
```
I believe that there are 2 ways to acomplish this:
```
1)to directly exchange `values` in memory
2)to change `n... |
Your values are very small, so I expect exchanging them to be more efficient than changing the pointer structure. As always, you will have to measure the actual performance in your use case to be sure.
|
So I'm having trouble getting even a simple Makefile to work. Heres what I have:
```
proj : driver.o
icc -g -O3 -openmp driver.o -o proj
driver.o : driver.c driver.h
icc -g -O3 -openmp driver.c
```
I feel like it's pretty straight forward. Proj only depends on driver.o which in turn depends on driver.c and d... |
You should giveicca-I.option to get it to look for include files in the current directory.
```
icc -I. -c -g -O3 -openmp driver.c
```
(I took the liberty of also adding the-cflag to prevent linking.)
|
So I have some specific environment (like linux os based phone) so I have no such thing like terminal. All I can do is create my own UI's using C++ and some SDK I am provided with.
I want to create an ssh client application for my device. Its not a work, nor a homework - just for fun that means I have lots of time fo... |
PuTTYfor example.
|
I'm developing an app in C using Gtk. I have a GtkCombo with some restrictions that should launch an error message when user selects wrong entries in the list. The problem is that when callback launches the error message, pop-down string is still open, and if the user moves the mouse over it, the list acts as if all e... |
Try connecting the signal withg_signal_connect_after()instead ofg_signal_connect(). The callback should run after the combo popdown has finished all its reactions to the click.
|
I have a
```
structure {
int a;
char b;
} st;
```
Is there a way to typecast the structure memberst.a?
Because in few places I want it asintand in few places I want it asChar*
|
I suggest to use aunion:
```
struct {
union {
int a;
char *ptr;
} u;
char b;
} st;
```
Under the assumption thatsizeof(int) == sizeof(char*)holds, you can access the same value in memory by either usingst.u.aorst.u.ptr.
For what it's worth, consider usingsize_tinstead ofintas the type of theafield. Th... |
So I am writing a C file which includes /extfs/ext2fs.h. I am trying to call the function ext2fs_open(). I can clearly see that the header file ext2fs.h has that particular function. In fact, if I pass in the incorrect number of arguments, it even corrects me. However it does not compile, always giving me a "undefined... |
You do need to link tolibext2fs, yes...
```
gcc -I/dir/containing/ext2fs.h -lext2fs your_source.c -o app
```
|
```
typedef struct {
float *numbers;
float val1;
float val2;
} Values;
Values val[16];
```
How can one allocate memory for numbers in the struct?
|
If you want to allocate the space for one float in the first element of your struct, you would do it like this:
```
#include <stdlib.h>
/* ... */
val[0].numbers = malloc(1 * sizeof(float)); /* "1 * " for clarity... */
```
If that's what you meant.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.