question
stringlengths
25
894
answer
stringlengths
4
863
I would like to store all paths to headers in separate file. I'm going to generate file with paths dynamically, to avoid re-creating Makefile whenever paths change. Is that possible?
Yes, you can generate the file, let's call itpaths.inc, so it looks like, for example: ``` INCLUDEPATH=path1:path2 ``` and then include the file in your mainMakefile ``` include paths.inc ``` and use the variable defined in it:${INCLUDEPATH}
I am trying to create a simple program usingGstreamerto take the input from a microphone and save it to a mp3 file. I keep getting Internal data flow error and can´t seem to find the problem(I am new toGstreamer). Here is a link to my code: http://pastebin.com/QDexe8Fz
Your code is not handling return codes from the functions. As a result your in the dark when it fails. Anyway in your code you forgot to link the elements. Right after line 70, also do gst_element_link_many(....);
I'm trying to find information on how to embed JavascriptCore in a C project. It's easy to find guides for both V8 and SpiderMonkey, but near impossible to find for JSC. Does anyone know where to look? I'd rather not embed V8 as it's C++, and i heard SpiderMonkey's API was horrible.
This link for theJavaScriptCore web pagesays that JavaScriptCore is a part of WebKit. Here is a link to theJavaScriptCore page within WebKit site. Thiswikipedia topic on webkitmentions history including a bit of information about JavaScriptCore. Here is someinformation about web kit from Apple. And here is an artic...
I was writing a structure from a book, and then see how it does initialization. I don't get it, how he does that. ``` struct node { char target[50]; char stack[50]; char *s,*t; int top; } ``` Initialization function: ``` void init { p->top = -1; strcpy(p->target,""); strcpy(p->stack,""); p-t = p->target; p...
He isnotdoing it. The statementstrcpy(p->target,"");doesnotinitialize the 50 positions of the array. It just puts a 0 in the first position. (See thisreference.)
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
You should take a look atGPG(GNU alternative to PGP). There alsoGnuTLSor well knownOpenSSLlibrary.
I'm working on a hw assignment and was wondering if someone with a bit more Unix experience could explain what is meant by the following question: ``` Run sample program 1 in the background with & Using the ps utility with appropriate options, observe and report the PIDs and the status of your processes. ``` Sample...
``` ./fork_demo & ps ``` Explanation: &forces the process before it (fork_demo) into the background. At that point, you can run another command (likeps).
While generating an XML content, I get an empty node<node/>, and I want it to be<node></node>. (Since<node></node>is the correct form of c14n, the progress called "converting empty elements to start-end tag pairs") How should I convert it? There's a way hinted by Jim Garrison(Thank you) to do this, by using xmlBuff...
Take a look at the libxml2 documentation, specificallyxmlSaveOptionvalueXML_SAVE_NO_EMPTY
This question already has answers here:Closed10 years ago. Possible Duplicate:Standard data structure library in C? Does C have any data structure implementations similar to the C++ STL? Specifically associative containers, hash maps or any other structure with approximately constant time retrieval? Thanks!
Ccan'thave an "exact equivalent" of STL because C doesn't have templates or classes. You might be interested in the "Glib collections" library: http://www.ibm.com/developerworks/linux/tutorials/l-glib/Gnome Glib:http://developer.gnome.org/glib/stable/GNU Gnulib:http://www.gnu.org/software/gnulib/
I am writing one tool and I need to gather some information about running Linux system beyond those that available fromsysinfo, as I understand many of them are available from/proc/file system, but I need to do it from the C language level, is there any system API for doing this or maybe I should just write functions ...
Theprocfilesystemisthe API: you read the pseudo-files to get the data. This can be done in any programming language, including C.
I know that an invalid pointer leads to undefined behaviour but how does free know whether a pointer is valid or not? Is there kind of a checksum at the beginning of each block in free list? something like: ``` if((*ptr) == 'CHECKSUM')) free else do something undefined ```
I know that an invalid pointer leads to undefined behaviour but how does free know whether a pointer is valid or not? The only check is whether the pointer is null or not. If it's a null pointer, free (by specification) will do nothing. Otherwise,freejust tries to "free" the memory, making the assumption that it wa...
FromSUSv4: If pid is negative, but not -1, sig shall be sent to all processes (excluding an unspecified set of system processes) whose process group ID is equal to the absolute value of pid, and for which the process has permission to send a signal. As I understand there can't be 2 or more processes with the s...
The spec says to all processeswithin the given group.There can be multiple processes per group. The negativeididentifies the group.
This question already has answers here:Closed11 years ago. Possible Duplicate:In C, how do I get a specific range of numbers from rand()? ``` #include <stdio.h> #include <stdlib.h> #include <time.h> int main(int argc, char** argv) { srand(time(NULL)); int r = rand(); printf("%d\n", r); return (EXIT_SUCCESS); } ...
``` int main(int argc, char** argv) { int i; int array[40]; srand(time(NULL)); for (i=0; i<40; i++) array[i] = rand()%6 + 1 return (EXIT_SUCCESS); } ```
I have a large buffer: ``` char *buf = malloc(1000000000); // 1GB ``` If I forked a new process, it would have a buf which shared memory with the parent's buf until one or the other wrote to it. Even then, only one new 4KiB block would need to be allocated by the kernel, the rest would continue to be shared. I'd l...
You'll want to create a file on disk or a POSIX shared memory segment (shm_open) for the block. The first time, map it withMAP_SHARED. When you're ready to make a copy and switch to COW, callmmapagain withMAP_FIXEDandMAP_PRIVATEto map over top of your original map, and withMAP_PRIVATEto make the second copy. This shou...
I am trying to create a simple program usingGstreamerto take the input from a microphone and save it to a mp3 file. I keep getting Internal data flow error and can´t seem to find the problem(I am new toGstreamer). Here is a link to my code: http://pastebin.com/QDexe8Fz
Your code is not handling return codes from the functions. As a result your in the dark when it fails. Anyway in your code you forgot to link the elements. Right after line 70, also do gst_element_link_many(....);
I'm trying to find information on how to embed JavascriptCore in a C project. It's easy to find guides for both V8 and SpiderMonkey, but near impossible to find for JSC. Does anyone know where to look? I'd rather not embed V8 as it's C++, and i heard SpiderMonkey's API was horrible.
This link for theJavaScriptCore web pagesays that JavaScriptCore is a part of WebKit. Here is a link to theJavaScriptCore page within WebKit site. Thiswikipedia topic on webkitmentions history including a bit of information about JavaScriptCore. Here is someinformation about web kit from Apple. And here is an artic...
I was writing a structure from a book, and then see how it does initialization. I don't get it, how he does that. ``` struct node { char target[50]; char stack[50]; char *s,*t; int top; } ``` Initialization function: ``` void init { p->top = -1; strcpy(p->target,""); strcpy(p->stack,""); p-t = p->target; p...
He isnotdoing it. The statementstrcpy(p->target,"");doesnotinitialize the 50 positions of the array. It just puts a 0 in the first position. (See thisreference.)
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
You should take a look atGPG(GNU alternative to PGP). There alsoGnuTLSor well knownOpenSSLlibrary.
I'm working on a hw assignment and was wondering if someone with a bit more Unix experience could explain what is meant by the following question: ``` Run sample program 1 in the background with & Using the ps utility with appropriate options, observe and report the PIDs and the status of your processes. ``` Sample...
``` ./fork_demo & ps ``` Explanation: &forces the process before it (fork_demo) into the background. At that point, you can run another command (likeps).
While generating an XML content, I get an empty node<node/>, and I want it to be<node></node>. (Since<node></node>is the correct form of c14n, the progress called "converting empty elements to start-end tag pairs") How should I convert it? There's a way hinted by Jim Garrison(Thank you) to do this, by using xmlBuff...
Take a look at the libxml2 documentation, specificallyxmlSaveOptionvalueXML_SAVE_NO_EMPTY
This question already has answers here:Closed10 years ago. Possible Duplicate:Standard data structure library in C? Does C have any data structure implementations similar to the C++ STL? Specifically associative containers, hash maps or any other structure with approximately constant time retrieval? Thanks!
Ccan'thave an "exact equivalent" of STL because C doesn't have templates or classes. You might be interested in the "Glib collections" library: http://www.ibm.com/developerworks/linux/tutorials/l-glib/Gnome Glib:http://developer.gnome.org/glib/stable/GNU Gnulib:http://www.gnu.org/software/gnulib/
Is it possible in C to send a hex value via UDP, through a GSocket using g_socket_send? I don't necessarily need to do any conversions one way or the other, but even when I manually enter a hex string as the gchar buffer in g_socket_send, it is sent as an ASCII string. Thank you in advance!
You are sendingbytes. You need to figure out what the other end expects, and build those bytes accordingly. Say, if your receiver wants binary data, then this might be it: ``` char buffer[4] = { 0xFF, 0x05, 0x01, 0xFE }; /* ... */ if ( g_socket_send( socket, buffer, 4, ... ) < 0 ) { /* handle error */ } ```
I know that the following two things are the same in c (because of offsets and arrays) ``` someArray[i] //ith element of someArray *(someArray + i) //ith element of someArray ``` However for structs, the same syntax doesn't seem to hold up very well... ``` someStruct[i]->*(someArray + j) //compiler error *(so...
AssumingsomeStructis an array of structs, andsomeArrayis a struct member of array type, then either of these would be valid: ``` *(someStruct[i].someArray + j) ``` or ``` (*(someStruct + i)).someArray[j] ``` See e.g.http://ideone.com/UtLN2.
I am trying to delete .txt extension from filename that is written in string "mat": ``` sscanf(mat, "%s.txt", ime_datoteke); ``` Ifmat="sm04567890.txt"I want thatime_datoteke="sm04567890". As in example I tried usingsscanf, but it doesnt work (it copies mat to ime_datoteke). How can I do it in C?
You could modify yoursscanfapproach slightly to read a string that does not include a.: ``` sscanf(mat, "%[^.].txt", ime_datoteke); ``` However, it would be best if you look for the.character from the end of the string, and then copy the substring determined by it. ``` char* dot = strrchr(mat, '.'); strncpy(ime_dat...
I am wondering why in the following programsizeof(int)returns a different value thansizeof(int*). Here is the small program: ``` int main(){ std::cout<<sizeof(int)<<endl; std::cout<<sizeof(int*)<<endl; return 0; } ``` And here is the output: ``` 4 8 ``` Till now I remember the size of a integer pointe...
The size of anintand anint*are completely compiler and hardware dependent. If you're seeing eight bytes used in anint*, you likely have 64-bit hardware, which translates into eight bytes per pointer. Hope this helps!
I'm wondering about theLPVOID lpParameterparameter of theCreateRemoteThreadfunction. Because processes don't share memory, the remote thread can't access a struct in our process. So, does the function copy the parameter and manages it by it own or do we need to allocate memory withVirtualAllocExand then callWriteProce...
CreateRemoteThreaddoes not do any automatic management oflpParameter. You are correct, it is up to the developer to ensure thatlpParameteris a valid pointer in the context of the target process.VirtualAllocExandWriteProcessMemoryare definitely options for doing so.
Another student asked me what could be wrong with his C code. I successfully reproduced the erroneous behavior and have completely no idea why this segfaults. Consider this tiny C programm: ``` #include <stdio.h> int main(void) { int N = 590; double A[N][N]; double B[N][N]; double C[N][N]; printf...
The amount of stack you have available to your app is very system dependent, and automatic variables (such as your double arrays) consume stack space. Calling a function requires additional stack space (for its variables, and housekeeping such as saved registers and a return point). You're going off the end of your st...
With anOOlanguage I often use a factory design pattern to connect to a DB: ``` // Connect to Redis ( PHP ) protected function get_redis() { static $redis = false; if( $redis === false ) { $redis = new Predis\Client(Configure::read('redis.db')); } return $redis; } ``` I done quite a lot ofCbut never...
I am going to disagree with you here. Factory method does not necessarily put an OO stamp on your code. It's just a pattern for creating things. If you don't want to create more than one connection, you can control that in theget_connectionfunction. This is another application for this pattern.
How can I search for a file within a directory and its sub-directories in C? I'm not allowed to usefindand I must useopendir,readdirandstat. I want to perform something like the commandls -lnif the file indeed exists.
For traversing the directories, you will need:opendir(3),readdir(3), andclosedir(3). For checking the type of file (to see if it's a directory and if you should recursively search within it) you will needstat(2). You will want to check ``` (struct stat).st_mode & S_IFDIR ``` to see if the file is a directory. See<...
As the heading goes, Is it possible for the main function return a pointer? If yes then where would be useful? Thanks!
Only a return type ofintis blessed by the standard: 5.1.2.2.1 Program startup1 The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:int main(void) { /* ... */ }or with two parameters (...
I'm trying to make a FOR loop in c with specific i values for example i=2,6,8,12,16,20,22,26,34.. I just don't know how to specify increments as they are not equal. This code is not good for me. ``` for (i=2,i<=30,i++) { } ``` Maybe with specified array of values in i and then run for loop with reference to that ar...
Yourfor-loop syntax needs to be fixed. The first option is to use a custom function: ``` for (i=2; i <= 30; i = foo(i)) { ... } ``` wherefoois a function which takes the current value ofiand returns the next value. You will need to come up with a proper definition offooyourself. The other approach can be to put al...
I get the following error with the following code. I tried to figure out where the problem is over Google, but I didn't find anything helpful. ``` Compiling /home/tectu/projects/resources/chibios/ext/lcd/touchpad.c In file included from /home/tectu/projects/resources/chibios/ext/lcd/touchpad.c:1:0: /home/tectu/projec...
volatileas a qualifier can be applied to a particular instance of structure.You are applying it to a type which is useless and the compiler correctly points it out.
Is it possible in C to send a hex value via UDP, through a GSocket using g_socket_send? I don't necessarily need to do any conversions one way or the other, but even when I manually enter a hex string as the gchar buffer in g_socket_send, it is sent as an ASCII string. Thank you in advance!
You are sendingbytes. You need to figure out what the other end expects, and build those bytes accordingly. Say, if your receiver wants binary data, then this might be it: ``` char buffer[4] = { 0xFF, 0x05, 0x01, 0xFE }; /* ... */ if ( g_socket_send( socket, buffer, 4, ... ) < 0 ) { /* handle error */ } ```
I know that the following two things are the same in c (because of offsets and arrays) ``` someArray[i] //ith element of someArray *(someArray + i) //ith element of someArray ``` However for structs, the same syntax doesn't seem to hold up very well... ``` someStruct[i]->*(someArray + j) //compiler error *(so...
AssumingsomeStructis an array of structs, andsomeArrayis a struct member of array type, then either of these would be valid: ``` *(someStruct[i].someArray + j) ``` or ``` (*(someStruct + i)).someArray[j] ``` See e.g.http://ideone.com/UtLN2.
I am trying to delete .txt extension from filename that is written in string "mat": ``` sscanf(mat, "%s.txt", ime_datoteke); ``` Ifmat="sm04567890.txt"I want thatime_datoteke="sm04567890". As in example I tried usingsscanf, but it doesnt work (it copies mat to ime_datoteke). How can I do it in C?
You could modify yoursscanfapproach slightly to read a string that does not include a.: ``` sscanf(mat, "%[^.].txt", ime_datoteke); ``` However, it would be best if you look for the.character from the end of the string, and then copy the substring determined by it. ``` char* dot = strrchr(mat, '.'); strncpy(ime_dat...
I am wondering why in the following programsizeof(int)returns a different value thansizeof(int*). Here is the small program: ``` int main(){ std::cout<<sizeof(int)<<endl; std::cout<<sizeof(int*)<<endl; return 0; } ``` And here is the output: ``` 4 8 ``` Till now I remember the size of a integer pointe...
The size of anintand anint*are completely compiler and hardware dependent. If you're seeing eight bytes used in anint*, you likely have 64-bit hardware, which translates into eight bytes per pointer. Hope this helps!
I'm wondering about theLPVOID lpParameterparameter of theCreateRemoteThreadfunction. Because processes don't share memory, the remote thread can't access a struct in our process. So, does the function copy the parameter and manages it by it own or do we need to allocate memory withVirtualAllocExand then callWriteProce...
CreateRemoteThreaddoes not do any automatic management oflpParameter. You are correct, it is up to the developer to ensure thatlpParameteris a valid pointer in the context of the target process.VirtualAllocExandWriteProcessMemoryare definitely options for doing so.
Another student asked me what could be wrong with his C code. I successfully reproduced the erroneous behavior and have completely no idea why this segfaults. Consider this tiny C programm: ``` #include <stdio.h> int main(void) { int N = 590; double A[N][N]; double B[N][N]; double C[N][N]; printf...
The amount of stack you have available to your app is very system dependent, and automatic variables (such as your double arrays) consume stack space. Calling a function requires additional stack space (for its variables, and housekeeping such as saved registers and a return point). You're going off the end of your st...
With anOOlanguage I often use a factory design pattern to connect to a DB: ``` // Connect to Redis ( PHP ) protected function get_redis() { static $redis = false; if( $redis === false ) { $redis = new Predis\Client(Configure::read('redis.db')); } return $redis; } ``` I done quite a lot ofCbut never...
I am going to disagree with you here. Factory method does not necessarily put an OO stamp on your code. It's just a pattern for creating things. If you don't want to create more than one connection, you can control that in theget_connectionfunction. This is another application for this pattern.
How can I search for a file within a directory and its sub-directories in C? I'm not allowed to usefindand I must useopendir,readdirandstat. I want to perform something like the commandls -lnif the file indeed exists.
For traversing the directories, you will need:opendir(3),readdir(3), andclosedir(3). For checking the type of file (to see if it's a directory and if you should recursively search within it) you will needstat(2). You will want to check ``` (struct stat).st_mode & S_IFDIR ``` to see if the file is a directory. See<...
As the heading goes, Is it possible for the main function return a pointer? If yes then where would be useful? Thanks!
Only a return type ofintis blessed by the standard: 5.1.2.2.1 Program startup1 The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:int main(void) { /* ... */ }or with two parameters (...
I'm trying to make a FOR loop in c with specific i values for example i=2,6,8,12,16,20,22,26,34.. I just don't know how to specify increments as they are not equal. This code is not good for me. ``` for (i=2,i<=30,i++) { } ``` Maybe with specified array of values in i and then run for loop with reference to that ar...
Yourfor-loop syntax needs to be fixed. The first option is to use a custom function: ``` for (i=2; i <= 30; i = foo(i)) { ... } ``` wherefoois a function which takes the current value ofiand returns the next value. You will need to come up with a proper definition offooyourself. The other approach can be to put al...
I am wondering why in the following programsizeof(int)returns a different value thansizeof(int*). Here is the small program: ``` int main(){ std::cout<<sizeof(int)<<endl; std::cout<<sizeof(int*)<<endl; return 0; } ``` And here is the output: ``` 4 8 ``` Till now I remember the size of a integer pointe...
The size of anintand anint*are completely compiler and hardware dependent. If you're seeing eight bytes used in anint*, you likely have 64-bit hardware, which translates into eight bytes per pointer. Hope this helps!
I'm wondering about theLPVOID lpParameterparameter of theCreateRemoteThreadfunction. Because processes don't share memory, the remote thread can't access a struct in our process. So, does the function copy the parameter and manages it by it own or do we need to allocate memory withVirtualAllocExand then callWriteProce...
CreateRemoteThreaddoes not do any automatic management oflpParameter. You are correct, it is up to the developer to ensure thatlpParameteris a valid pointer in the context of the target process.VirtualAllocExandWriteProcessMemoryare definitely options for doing so.
Another student asked me what could be wrong with his C code. I successfully reproduced the erroneous behavior and have completely no idea why this segfaults. Consider this tiny C programm: ``` #include <stdio.h> int main(void) { int N = 590; double A[N][N]; double B[N][N]; double C[N][N]; printf...
The amount of stack you have available to your app is very system dependent, and automatic variables (such as your double arrays) consume stack space. Calling a function requires additional stack space (for its variables, and housekeeping such as saved registers and a return point). You're going off the end of your st...
With anOOlanguage I often use a factory design pattern to connect to a DB: ``` // Connect to Redis ( PHP ) protected function get_redis() { static $redis = false; if( $redis === false ) { $redis = new Predis\Client(Configure::read('redis.db')); } return $redis; } ``` I done quite a lot ofCbut never...
I am going to disagree with you here. Factory method does not necessarily put an OO stamp on your code. It's just a pattern for creating things. If you don't want to create more than one connection, you can control that in theget_connectionfunction. This is another application for this pattern.
How can I search for a file within a directory and its sub-directories in C? I'm not allowed to usefindand I must useopendir,readdirandstat. I want to perform something like the commandls -lnif the file indeed exists.
For traversing the directories, you will need:opendir(3),readdir(3), andclosedir(3). For checking the type of file (to see if it's a directory and if you should recursively search within it) you will needstat(2). You will want to check ``` (struct stat).st_mode & S_IFDIR ``` to see if the file is a directory. See<...
As the heading goes, Is it possible for the main function return a pointer? If yes then where would be useful? Thanks!
Only a return type ofintis blessed by the standard: 5.1.2.2.1 Program startup1 The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:int main(void) { /* ... */ }or with two parameters (...
I'm trying to make a FOR loop in c with specific i values for example i=2,6,8,12,16,20,22,26,34.. I just don't know how to specify increments as they are not equal. This code is not good for me. ``` for (i=2,i<=30,i++) { } ``` Maybe with specified array of values in i and then run for loop with reference to that ar...
Yourfor-loop syntax needs to be fixed. The first option is to use a custom function: ``` for (i=2; i <= 30; i = foo(i)) { ... } ``` wherefoois a function which takes the current value ofiand returns the next value. You will need to come up with a proper definition offooyourself. The other approach can be to put al...
I get the following error with the following code. I tried to figure out where the problem is over Google, but I didn't find anything helpful. ``` Compiling /home/tectu/projects/resources/chibios/ext/lcd/touchpad.c In file included from /home/tectu/projects/resources/chibios/ext/lcd/touchpad.c:1:0: /home/tectu/projec...
volatileas a qualifier can be applied to a particular instance of structure.You are applying it to a type which is useless and the compiler correctly points it out.
I have a header with the following style of declarations: ``` extern struct xvimage *allocimage(char * name, int32_t rs, int32_t cs, int32_t ds, int32_t t); extern struct xvimage *allocmultimage(char * name, int32_t rs, int32_t cs, int32_t ds, int32_t ts, int32_t nb, int32_t t); etc... ``` Trying to compile it yield...
Theint32_ttype is defined in the<stdint.h>header, so make sure that one is included at the top of your header file.
Why does this code print 4 as the output? Please also provide some details to help me to understand this type of behaviour better. ``` int main(){ int *p=NULL; printf("%d" ,p+1); return 0; } ```
You're setting a pointer to 0 (NULL) and then adding 1 to it; then you're converting the result to anintand printing the result. The key piece of knowledge you need here is that when you increment (add 1 to) a pointer, you actually add the size of the pointed-to object -- anintpointer is advanced to point to thenextin...
What is the linux API to query the status of a thread, like thetop -Hcommand can do? I do not need portability, it just has to work on modern x86[_64] linux. I do not want to only know if the thread is alive or terminated. I need to know if it's sleeping also.
As far as I knowtopreads its information from/proc, on Linux at least. Update: Fortop's sources you might like to read here:Procps - The /proc file system utilities
In this code, why issizeof(x)the size of a pointer, not the size of the typex? ``` typedef struct { ... } x; void foo() { x *x = malloc(sizeof(x)); } ```
Because C says: (C99, 6.2.1p7) "Any other identifier has scope that begins just after the completion of its declarator." So in your example, the scope of the objectxstart right after thex *x: ``` x *x = /* scope of object x starts here */ malloc(sizeof(x)); ``` To convince yourself, put another object de...
How would I go about printing a process id before the process is actually executed? Is there a way I can get the previously executed process id and just increment? i.e. ``` printf(<process id>); execvp(process->args[0], process->args); ```
execfamily of syscalls preserve current PID, so just do: ``` if(fork() == 0) { printf("%d\n", getpid()); execvp(process->args[0], process->args); } ``` New PIDs are allocated onfork(2), which returns0to child process and child process' PID to parent.
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.Closed11 years ago. ``` ‎#include<stdio.h> int main() ...
"STACK" is never outputted. This is because the conditional part of theforstatement is always false (assumingNULLis#defined as(void *)0.
I can replace a string inside an ELF binary if it has smaller or equal length but a segfault happens when replacing with a longer string. Why does it segfault? What other things must be changed so it works?
I can replace a string inside an ELF binary if it is less than or equal length Depending on whether you are talking about a fully linked binary (ET_EXECorET_DYN) or an object file (ET_REL), your statement above may or may not be correct. You can't safely edit a string in.dynstrsection of a fully-linked binary, becau...
I have this function: ``` int firstHeapArray (IntHeapArray h) { if(!emptyHeapArray(h)) return h.array[0]; } ``` It's declared as int, and this is the IntHeapArray struct: ``` typedef struct intHeapArray { int *array; int size; } IntHeapArray; ``` Can you say why I get this warning while compili...
The error message is stating that you have a method that is not avoidreturn, but you're reaching the end without returning a value. You need to return a valid int value. The problem is here: ``` int firstHeapArray (IntHeapArray h) { if(!emptyHeapArray(h)) return h.array[0]; // If emptyHeapArray(h) ...
The download page for cmake only shows a 32 bit installer for windows. Any idea how to install it on 64 windows systems.
There is really no reason for a 64bit native CMake. CMake is only building theconfiguration, so you can use it to build configurations for 64bit software, even with the 32bit version. That being said, if you truly want a 64bit native version, you could always download the source and compile it. There is no 64bit in...
I am new to the win32 api and need help trying to understand how the GetLogicalDrives() function works. I am trying to populate a cbs_dropdownlist with all the available drives that are not in use. here is what I have so far. I would appreciate any help. ``` void FillListBox(HWND hWndDropMenu) { DWORD drives = GetLo...
The functionGetLogicalDrivesreturns abitmaskof the logical drives available. Here is how you would do it: ``` DWORD drives = GetLogicalDrives(); for (int i=0; i<26; i++) { if( !( drives & ( 1 << i ) ) ) { TCHAR driveName[] = { TEXT('A') + i, TEXT(':'), TEXT('\\'), TEXT('\0') }; SendMessage(hWn...
I have an array which is sorted in descending order, with no duplicates. Can I perform binary search on it using bsearch function in libc ? To do this, do I need to alter the compare function that I am passing to it ? Thanks
Yes, you can usebsearch. You will need to make sure yourcomparefunction agrees with the sort order of your array. In your case that might mean logically inverting the normal ascending/equal/descending order.
I've a project that has .C codes generated from Simulink Models (using RTW). The executable needs to be generated for a LynxOS RTOS, I use cygwin, but its too slow, takes several hours to compile & link some ~ 650 .C code files and libraries. I was wondering if its possible to put those sources & libraries for share ...
The ways you can tackle this listed from fastest to slowest: Native Linux through dual-boot and a shared diskVirtualbox/VMWare Player with a distributed version control pulling the sources on the VM's disk.Virtualbox/VMWare Player with a shared or network folder.Cygwin. The tradeoff between 2 and 3 is disk access. S...
I want to see how printf (and many other functions) works. I wrote ``` #include <Windows.h> #include <stdio.h> int main() { printf(""); return 0; } ``` in main.c code and go to definition in the right click menu but it shows something like ``` _Check_return_opt_ _CRTIMP int __cdecl printf(_In_z_ _Printf_format_st...
Here you go: http://sourceware.org/git/?p=glibc.git;a=blob;f=stdio-common/vfprintf.c;h=d5690342536bc8cf948c786f663bb63f73f91f3a;hb=HEAD. This is from the GNU C library implementation (GLIBC).
On Windows,statand pretty much all other C/POSIX functions Windows supplies are defined in msvcrt.dll, which is the C runtime library. On Linux, I know a lot of POSIX C functions are system calls. I also know when linking a program, you can't have undefined references. I have searched allsofiles in/liband/usr/libfor ...
On my Linux machine, I can find thestat(weak) symbol and__stat(non-weak) in/usr/lib/libc.a
How can one tell, given avoid *pointer, what is the size of a block allocated on this given address (previously allocated usingmalloc; in Linux and Windows)? I hope both systems surely store this kind of information somewhere. That is, alternative ofmalloc_sizewhich exists on OSX/Darwin. Using gcc/mingw if it helps.
On Windows, things that use the MS CRT can use_msize, on Linux you could trymalloc_usable_size...
I know for malloc sbrk is the system call invoked ,Similarly What is the system cal invoked when i write to a malloed memory(heap memory) ``` int main { /* 10 byte of heap memory allocated */ char *ptr = malloc(5); ptr[0] = 10; // **What is the system call invoked for writing into this...
There are no system call involved in this case. Ask you compiler to generate assembly so that you can see that there is only some MOV instructions there. Or you can use a debugger to see the assembly
Is it a WARRANTY, that offset of first element of structure is 0? To be more accurate, lets consider ``` struct foo { int a; double b; }; struct foo *ptr=malloc(sizeof(struct foo)); int *int_ptr = &ptr->a; free(int_ptr) ``` Is it garantied, that it is valid always, under any os or any other factors?
Yes it is guaranteed. Will get you a standard quote, let me lookup. C99 Standard: §6.7.2.1 Para 12 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared.A pointer to a structure object, suitably converted,...
I need to store a pointer to a char array in a struct, and then modify/access the arrays content. How can I do that? I can only think of something similar to this, but I don't get to the complete compilable solution. ``` struct foo { unsigned char *array; }; ``` And then: ``` unsigned char array[512]; struct f...
Your code is almost fine: ``` foo->array[0] = 'K'; ``` The problem with your code*(foo->array[0])is that you try to dereference acharwhich is not even a pointer. You also need to allocate memory for the struct - currentlyfoopoints to some random memory location where an access will most likely crash your program: ...
[It seems odd this doesn't exist, so apologies in advance if it's a duplicate] I want to test for logical equality in C. In other words, I want to know whether two values would be equal if both were converted in the normal way associated with logical expressions. In C99, I think that ``` (bool)a == (bool)b ``` gi...
You typically see this: ``` if ((a == 0) == (b == 0)) ``` Or ``` if (!!a == !!b) ``` Since!!aevaluates to 1 if a is nonzero and 0 otherwise. Hope this helps!
Under Windows I use MultiByteToWideChar(CP_ACP, ...) and WideCharToMultiByte(CP_UTF8, ...) for the conversion. How do I do the same thing under OS X and Linux? I tried mbstowcs/wcstombs but the resulting char* is not UTF-8.
Look intoiconv(3). that's the api you want. You'll need-liconv.
if possible then how to return more than one value. It can not be because of return is done through Accumulator in controller or CPU. Is this is the correct reason?
Because that's how the language is defined. There is no fundamental reason; other languages can return multiple values (e.g. Matlab). As a "workaround", you can return a struct that contains multiple fields.
I am currently working on a project where I need to find the oldest file from a base name within the directory. For example the base name of the file may be mylog but it will need to look at all files like mylog_060620121421.txt. From all the files that are mylog_ I need to find out which file is the oldeest, i.e. cr...
On linux just type in the dir: ``` ls -trl ``` This gives a list, beginning with the oldest file. If you want the name directly you can get it with: ``` ls -tr | head - 1 ```
I was at an interview today, and was asked the difference between the following two declarations: ``` int *A[10]; ``` and ``` int (*A)[10]; ``` which I did not know. If you think I am missing some important pointer 'pointer', please let me know that too. Thanks.
The first declares an array of ten pointers toint, the second a pointer to an array of tenints. The[]binds tighter than the*, so the first could equivalently be written ``` int *(A[10]); ```
According to K&R C section 1.6, acharis a type of integer. So why do we need%c. And why can't we use%dfor everything?
Because%dwill print the numeric character code of thechar: ``` printf("%d", 'a'); ``` prints97(on an ASCII system), while ``` printf("%c", 'a'); ``` printsa.
What is the difference between_m256iand_m256dand_m256? andWhat is the difference between_m128iand_m128dand_m128?
Rule of thumb: anisuffix is used for allintegervector types,dis fordouble precisionfloating point vector types, and when there is no suffix it's forsingle precisionfloating point vector types.
Using Eclipse, working with (ANSI) C language, is there any way to view the values that pointers are pointing on from debug? Thanks
I haven't used Eclipse in years, but isn't there a "watch" window, where you can add variables to watch? In that case you should be able to just put*pointerin there.
My C code: ``` #include<stdio.h> #include "Python.h" int main() { printf("Hello World"); return 0; } ``` I havepython-devinstalled for python2.7. Moreover,Python.his available in/usr/include/python2.7. gcc myfile.c# Python.h: No such file or directory I even tried :gcc -L/usr/include/python2.7/ myfile.c# ...
It should be-I, not-L: ``` gcc -I/usr/include/python2.7 myfile.c ```
Under Windows I use MultiByteToWideChar(CP_ACP, ...) and WideCharToMultiByte(CP_UTF8, ...) for the conversion. How do I do the same thing under OS X and Linux? I tried mbstowcs/wcstombs but the resulting char* is not UTF-8.
Look intoiconv(3). that's the api you want. You'll need-liconv.
if possible then how to return more than one value. It can not be because of return is done through Accumulator in controller or CPU. Is this is the correct reason?
Because that's how the language is defined. There is no fundamental reason; other languages can return multiple values (e.g. Matlab). As a "workaround", you can return a struct that contains multiple fields.
I am currently working on a project where I need to find the oldest file from a base name within the directory. For example the base name of the file may be mylog but it will need to look at all files like mylog_060620121421.txt. From all the files that are mylog_ I need to find out which file is the oldeest, i.e. cr...
On linux just type in the dir: ``` ls -trl ``` This gives a list, beginning with the oldest file. If you want the name directly you can get it with: ``` ls -tr | head - 1 ```
I was at an interview today, and was asked the difference between the following two declarations: ``` int *A[10]; ``` and ``` int (*A)[10]; ``` which I did not know. If you think I am missing some important pointer 'pointer', please let me know that too. Thanks.
The first declares an array of ten pointers toint, the second a pointer to an array of tenints. The[]binds tighter than the*, so the first could equivalently be written ``` int *(A[10]); ```
According to K&R C section 1.6, acharis a type of integer. So why do we need%c. And why can't we use%dfor everything?
Because%dwill print the numeric character code of thechar: ``` printf("%d", 'a'); ``` prints97(on an ASCII system), while ``` printf("%c", 'a'); ``` printsa.
What is the difference between_m256iand_m256dand_m256? andWhat is the difference between_m128iand_m128dand_m128?
Rule of thumb: anisuffix is used for allintegervector types,dis fordouble precisionfloating point vector types, and when there is no suffix it's forsingle precisionfloating point vector types.
Using Eclipse, working with (ANSI) C language, is there any way to view the values that pointers are pointing on from debug? Thanks
I haven't used Eclipse in years, but isn't there a "watch" window, where you can add variables to watch? In that case you should be able to just put*pointerin there.
My C code: ``` #include<stdio.h> #include "Python.h" int main() { printf("Hello World"); return 0; } ``` I havepython-devinstalled for python2.7. Moreover,Python.his available in/usr/include/python2.7. gcc myfile.c# Python.h: No such file or directory I even tried :gcc -L/usr/include/python2.7/ myfile.c# ...
It should be-I, not-L: ``` gcc -I/usr/include/python2.7 myfile.c ```
How do I remove for example2from123and returns13, by using bitwise operators? I have no idea how to do this.. it's possible? Thanks in advance.
What you're suggesting is possible, but wouldn't really make sense to do. Below are the values representations in bits (only showing relevant bits, everything further left is a zero): 2: 000010 || 123: 1111011 || 13: 001101 There's no logical way to change 123 into 13 with bitwise operations. It would better to turn...
How can I dump all the global variables and the address offsets in my executable? This is on os x, app developed with xcode compiled with gcc. Thank you
If Compiled to Mach-O Either useotoolor thecctools. If Compiled to ELF You should be able to do this withobjdumpand/orreadelf. I don't have a *nix system at hand here, butobjdump -s -j .datashould be getting you rather close enough.
My program is very simple, ``` ... #define TO_INT(a) (*(int *)a) void *pool_head; void *pool_tail; ... pool_head = sbrk(BUF_LENGTH); if (pool_head == (void *)-1) { errno = ENOMEM; return pool_head; } pool_tail = sbrk(0); TO_INT(pool_head) = BUF_LENGTH * -1; TO_INT((pool_tail - 3)) = BUF_LENGTH * -1; ``` ...
First, you cannot perform pointer arithmetic (pool_tail - 3) onvoid *. Second, even if we allow it and treatpool_tailaschar *, subtractingpool_tailby 3 does not give enough room to fit anint.
I have an FPGA that is hosting a website with an html and javascript front end and a C backend (ugh). Is there anyway to send a file from the C backend to the client? I'm talking to the backend via an html form (since the back end is hosted on an FPGA I'm unsure how it will handle AJAX). Some tricky points, the web...
No, this is possible. You just need to ensure the relevant HTTP headers are set in theGETresponse. SpecificallyContent-typeandContent-Disposition. e.g.: ``` Content-type: application/pdf Content-Disposition: attachment; filename="downloaded.pdf" ```
I have gone throughsizeof operator equivalent. ``` size_t size = (size_t)(1 + ((X*)0)); ``` But could not able to understand what is the meaning of(int*)0 or (int*)1000. What does ittellto the compiler? And whyone is addedto them? Could you please elaborate it.
(int *)0means "treat 0 as the address of an integer". Adding one to this obtains the address of the "next" integer in memory. Converting the result back to an integer therefore gives you the size of an integer. However, this relies onundefined behaviour, so you shouldn't use it.
For initialising all the elements of a 100×100 two-dimensional array, we can do it in two ways: Method 1: ``` int a[100][100]; for(i=0; i<100; i++){ for(j=0; j<100; j++){ a[i][j] = 10; } } ``` Method 2: ``` int a[100][100]; for(j=0; j<100; j++){ for(i=0; i<100; i++){ a[i][j] = 10; }...
The first method, since that will access the array sequentially. C stores 2-dimensional arrays inrow-majororder, meaning that a[i][j] will be adjacent to a[i][j+1] but not adjacent to a[i+1][j]. Yet another way to say the same thing (that generalizes to >2 dimensions) is that the rightmost index is adjacent in memor...
I letgcccompile the following example using-Wall -pedantic: ``` #include <stdio.h> int main(void) { printf("main: %p\n", main); /* line 5 */ printf("main: %p\n", (void*) main); /* line 6 */ return 0; } ``` I get: ``` main.c:5: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘int (*)()’ m...
This is essentially the only portable way to print a function pointer. ``` size_t i; int (*ptr_to_main)() = main; for (i=0; i<sizeof ptr_to_main; i++) printf("%.2x", ((unsigned char *)&ptr_to_main)[i]); putchar('\n'); ```
Unlike themalloc, I have never seen aifstatement for checking whether the array has got enough space. So is it guranteed that the arrays always get enough space even though they are allocated in the stack? And what to do in case otherwise?
No guarantee at all. There's no way to verify whether the stack allocation was successful or not. The C standard doesn't mandate any limits (min or max). So you should check with your operating system which typically allocates a fixed size stack. For example, on my Ubuntu system, the stack size is1MB. So it depends ...
I'm writing a TCP server. Everything it has to do is to read/write text to/from TCP sockets and read/write this text to/from text files on the file system where the server runs. If there's a problem with the connection (e.g. the client closes the socket), the server blocked on a read/write receives a SIGPIPE signal. ...
Many server programs choose to ignoreSIGPIPE, and use the return codes fromread/writeto have better understanding of the disconnection. For example,read/recvreturns0on a proper disconnect from the other end, and-1on error witherrnoset to one of multiple alternatives.
Is there any way to know / warn if a global variable is uninitialized with gcc ? I got it for local/ atomic variables “-Wuninitialized”
No!Global and static variables are initialized implicitly if your code doesn't do it explicitly as mandated by the C standard.In short, global and static variables are never left uninitialized.
Can any one explain what algorithm used instrcmpto compare two string in C programming ? I didnt understand the return value from this, It uses any algorithm like 'Levenstien algorithm' to find out distance between two string...
The GNU implementation of the standard C library, glibc, is open source and you can just readstrcmp.cif you are curious. There is not much to it. Here it is: ``` /* Compare S1 and S2, returning less than, equal to or greater than zero if S1 is lexicographically less than, equal to or greater than S2. */ int ...
I was told by an experienced programmer(spoj,codechef,topcoder etc ) than as a general rule one can use int for values upto 10^9. What is the general rule for using signed long int, unsigned long int, signed long long int, unsigned long long int
The answer to this question is platform dependent (because different platforms may have different sizes of integers). You can find a fairly complete list of limits athttp://en.cppreference.com/w/cpp/types/numeric_limits
I was wondering if can be posible to access the actual member of a union by the union address and not by the->&.operators. If that is posible, is that allowed?
you can access the memory of the union using the addressof operation&(union) e.g. ``` union foo { int32_t bar; int64_t baz; } afoo; void * address = &afoo; ``` But the point of a union is to allow transparent access to a 'shared' region of data that composed of different types; if you wantedchar *access to the...
I was trying to count how many out of my four variables were greater than 0, so I wrote these if statements to achieve my purpose. All numbers will be positive or 0: ``` if(a1>0){counter++;} if(a2>0){counter++;} if(a3>0){counter++;} if(a4>0){counter++;} printf("%d", co...
If you're looking for a single statement, ``` counter+= (a1>0) + (a2>0) + (a3>0) + (a4>0); ``` Should do. If you decide to pack your data into an array, ``` #define SIZE(x) (sizeof(x)/sizeof*(x)) int x, a[4]; for(x=0; x<SIZE(a); x++) counter += (a[x]>0); ``` Is still reasonably compact.
How would I output text one letter at a time like it's typing without using Sleep() for every character?
Sleep is the best option, since it doesn't waste CPU cycles. The other option is busy waiting, meaning you spin constantly executing NoOps. You can do that with any loop structure that does absolutely nothing. I'm not sure what this is for, but it seems like you might also want to randomize the time you wait between ...
I have a union with the declaration: ``` union test_u { int i; char *str; }; ``` I am trying trying to initialize a variable with data in the "second" field, using the code: ``` union test_u test = {"Sample"}; // char *, not int ``` On attempting to compile this, I receive the error: file.c:72:11: warnin...
In C99, this is possible usingdesignated initialisers: ``` union test_u test = { .str = "Sample" }; ```