question
stringlengths
25
894
answer
stringlengths
4
863
I was reading this article on MSDN"Managing Heap Memory in Win32" And in it they are explaining about a tool called ProcessWalker.exe In the article they explained that they can use this tool to explore the contents of virtual memory of any process. Does anyone know where I can download this tool from. Or maybe ProcessWalker might be deprecated. Does anyone know any other such tool?And I don't understand how is it even possible for such a tool to exist, wouldn't such a tool cause security breach?
17 years is areallylong time ago. Forget everything it says about GlobalAlloc and LocalAlloc. The SysInternals'VMMap utilitydoes a similar job, it is excellent.
I want to make a simple just-in-time compiler with c on Linux. How can I allocate memory such that I can write out raw x86 code to it and execute it as any other function?
See mprotect(). Once you have filled a (n-)page-sized memory region (allocated with mmap()) with code, change its permissions to disallow writes and allow execution.
I noticed that Snipping Tool (On Windows Vista / 7) has a Toolbar control. I'v used Spy++ and copied its exact styles but when I press down, it does not do like theirs. Theirs stays stuck on the clicked control, indicating that this tool is 'in use' I want to have this effect in my application. Thanks
I don't have a NT6 system near me ATM but I think you are just talking about the BSTYLE_CHECK toolbar button style
I want to rewrite a particular block in a file but its not working for me For example if I want to rewrite to offset 4 of the file I used lseek(fd,4,SEEK_SET) and called write system call but its writing at the end of the file instead of at offset 4.
Don't useO_APPEND. It will append everything to the end of the file, regardless of your seeking. Use: ``` open("file.txt", O_RDWR); ``` You're assuming the file already exists, so I don't see why you would useO_CREAT.
How could I create a control that looks like this one:http://img195.imageshack.us/img195/4268/eeeeae.png http://img195.imageshack.us/img195/4268/eeeeae.png I just want that small end. Thanks
If that's a Windows ComboBox control with a visual style applied to it, you can render its themed button wherever you like usingDrawThemeBackground()andCP_DROPDOWNBUTTON.
By default tabs get added from right to left, so if I insert 1,2,3,4,5 then the tabs will read 5,4,3,2,1. How can I make it read 1,2,3,4,5 thanks.http://img96.imageshack.us/i/ahhh.png/ http://img96.imageshack.us/i/ahhh.png This is obtained from inserting Untitled Project first and Untitled 5 last. What I would want would be for Untitled 5 to be selected at the far right and for Untitled Project to be at the far left and the ones inbetween following this idea...
If you are using win32 to insert the tabs, both the TCM_INSERTITEM and TabCtrl_InsertItem take the index of the tab as an argument. If you increment the index you insert the tabs in, as per theexample on msdn, then they are inserted left-to-right. If you insert every tab at index 0, newer tabs push the existing tabs to the right and you get them reversed.
I want to make a control where the bottom is nice and beveled as seen here:http://img19.imageshack.us/f/finalzh.png/ alt text http://img19.imageshack.us/f/finalzh.png/ What style must I add to my control to achieve the same look as this? Thanks
You could create a static control with a WS_EX_CLIENTEDGE or WS_EX_WINDOWEDGE extended style, and place it in a containing child window, which clips the top and sides so you only see the bottom bevel. Looking at the picture, you may even not need the child window - just position the static window at -4x-4 (use GetSystemMetrics SM_CX_BORDER to find out the real size of the window border) and size it 2x the border width larger that needed.
Before I start building one myself; Is there a wrapper for C or C++ which does the same thing asSVNKit?
There is an API provided in C - see theSubversion Documentation
I'm using a Win32 Header. I want to make it so that the header item I click on stays 'selected' or looks selected until I press another one. I want to avoid disabling it for aesthetic reasons. Thanks
If this header is part of a listview, you can provide a visual clue withListView_SetSelectedColumn
i am going to read a TDMS file in matlab using Mexfunction in C language in a 64 bit windows machine, but i will develop the app in 32 bit windows machine. i know in there is a difference between 32 bit machine and 64 bits with the size of variables. i used a lot of fread(.. sizeof(type)..). is it going to be a problem when it is running in 64 bit machine? if so, how can i make it portable to 64 bits mahince? thanks
ISO C99 provides the header <stdint.h>, which defines, amongst others, types of the form intN_t and uintN_t, where N is the width of the corresponding integer or unsigned integer type. If an implementation provides integer types of width 8, 16, 32 or 64, it should provide the corresponding typedefs.
Where arepointersandglobal variablesstored inC? Are they saved in the memory, heap or stack?
Global variables can be in a couple places, depending on how they're set up - for example,constglobals may be in a read-only section of the executable. "Normal" globals are in a read-write section of the executable. They're not on the heap or the stack at all. Pointers are just a type of variable, so they can be wherever you want them to be (on the heap if youmalloc()them, on the stack if they're local variables, or in the data section if they're global).
Why are reference variables not present/used in C? Why are they designed for C++?
Because C was invented first. I don't know if they hadn't thought about references at the time (being mostly unnecessary), or if there was some particular reason not to include them (perhaps compiler complexity). They're certainly much more useful for object-oriented and generic constructs than the procedural style of C.
I am using CDT for developing C programs. When the debugger stops on a break point and I do "Step Over" or "Step Into" the debugger behaviour is based on the source line level but not on the instruction level. Can I do debugging on the instruction level in CDT?
In theDebugwindow (Debug perspective) there is anInstruction Stepping Modebutton: It looks like a small i with an arrowi=>).You can also set breakpoints on specific instructions in the Disassembly window.
Once again, GCC is making me feel like an idiot for having trouble with the simplest things. I've included a header: ``` #include "PDL.h" ``` Then, I try to compile: ``` arm-none-linux-gnueabi-gcc -I/cygdrive/c/PalmPDK/include -I../lua-5.1.4/lua-webos/include -O2 -Wall -shared -nostdlib -mcpu=arm1136jf-s -mfpu=vfp -mfloat-abi=softfp -lpdl ``` But it says: PDL.h: no such file or directory I can change into the include directory I specified above and see PDL.h is there, but GCC just doesn't see it.
/cygdrive is something specific to cygwin, so if gcc isn't compiled to use the cygwin unix emulation layer, it won't search it. Try using-IC:/PalmPDK/include.
I want to be able to know how much room a particular tab takes up, is there a way to calculate this knowing it's text and having its item struct? Thanks
Assuming a SysTabControl how aboutTCM_GETITEMRECT?
This question already has answers here:Closed13 years ago. Possible Duplicate:C pointer to array/array of pointers disambiguation In C, isint *thing[5]an array of five pointers, each pointing to an integer, or a pointer to an array of five integers?
[]trumps*per theC precedence tablewhich means you have an array of five int pointers.
This question already has answers here:Closed13 years ago. Possible Duplicates:what does malloc(0) return ?what’s the point in malloc(0)? Why does malloc(0) return valid memory address ? What's the use ?
If the size of the space requested is 0, the behavior is implementation-defined: the value returned shall be either a null pointer or a unique pointer. Source:mallocat The Open Group
is "register struct" legal? In terms of standards and (separated from standards) in Gcc?
Yes. (No citation, there is simply no prohibition on that. There is a note assuming that the use of register with arrays is valid, and arrays are far more second class citizen in C that structs).
Is there an easy way to read/write a nibble in a byte without using bit fields? I'll always need to read both nibbles, but will need to write each nibble individually. Thanks!
Use masks : ``` char byte; byte = (byte & 0xF0) | (nibble1 & 0xF); // write low quartet byte = (byte & 0x0F) | ((nibble2 & 0xF) << 4); // write high quartet ``` You may want to put this inside macros.
This question already has answers here:Closed13 years ago. Possible Duplicate:what is the difference between const int*, const int * const, int const * ``` Are there any Difference between const char* p and char const* p ```
const char* pis a pointer to aconst char. char const* pis a pointer to achar const. Sinceconst charandchar constis the same, it's the same. However, consider: char * const pis aconstpointer to a (non-const) char. I.e. you can change the actual char, but not the pointer pointing to it.
I am trying to write a very small SNMP trap receiver, listening to UDP port 162. Traps come in fine, but I can not decode them. I have found libber, but it can't decode the traps for some reason. I am probably using it wrong. I imagine decoding an SNMP trap should be fairly simple and that I am missing something crucial. Is it possible to use NET-SNMP as a library and create a small trap-receiving program from it? I would not be surprised at all, but can not find any information about it. Maybe my google-fu is weak.
Well, using net-snmp, you usually use snmptrapd daemon that calls for you external commands/scripts. If you cannot use this way, I suggest you look at snmptrapd.c code. Moreover, if I recall correctly, they build a libsnmptrapd library. It should be easy to find the right API calls ... If I have time I will update my answer with a snippet ... my2c
I am currently developing a programming language in C, and I want to allow users to create apparently "unlimited" arrays with numerical indices without sacrificing performance in the process. For example,table [1000000000]would ideally be creatable and accessible in an instant without the memory overhead of a table of 1,000,000,000 items, 999,999,999 of which were unused; but the array would also perform well whentable [n]was defined for, say, 1 ≤ n ≤ 1000000. Do you have suggestions for the implementation of such an array-handling system?
There's Judy Arrayshttp://judy.sourceforge.net/
I have UTC time which is coming from UDP, I have a program to calculate Day and Time of UTC, how can I set my system clock at that day and time, kindly give me some direction so that I can make it possible. I am using Window OS.
To set the current system time, use theSetSystemTimeWin32 API function.
In C, what will happen if I supply a signed integer especifically a negative integer as the 3rd argument to the memcpy function? Example: ``` memcpy(destBuf, source, -100*sizeof(source)) ``` Will the result of-100*sizeof(source)be interpreted by memcpy as unsigned? Thanks!
the last parameter is unsigned. so by doing -100 * sizeof( source ) you'll get a huge number (That will wrap around, ie overflow). This is equivalent to doing "4,294,967,196 * sizeof( source )". Edit: Actually thats wrong I just realised. It will do -100 * sizeof( source ) and then convert it to an unsigned. For example if sizeof( source ) is 4 then it will convert -400 to unsigned and give you 0xFFFFFE70 (4,294,966,896).
As documented: "If not all tabs can be shown at once, the tab control displays an up-down control so that the user can scroll additional tabs into view." http://msdn.microsoft.com/en-us/library/bb760550%28VS.85%29.aspx I don't want this. I don't want an up down control to show if I have too many and I don't want multiline tabs. I want a single strip. I will handle the case of too many tabs with a control I create myself, but I don't want the up-down control. Thanks
There's no style for that, so i believe the only way is a bit of hacking. From what i can see with my Spy++, the updown control is a true child control of the tab control with id = 1. So, you can actually hide it with ShowWindow().
I am using C language and Linux as my programming platform in embedded device. My question is, how to correctly retrieve the current processor time(tick). I am using clock() function in time.h and it seems I am getting inconsistent value. Thanks.
Theclock()function measures the CPU time consumed by your process. It doesn't increment while your process is sleeping or blocked. If you want a high resolution clock that advances continually, useclock_gettime(CLOCK_MONOTONIC, ..).
Is there a way for windows created with WS_CHILD to inherit the parent's background color rather than default to Dialog Color? I'm trying to do this for a tab control, mainly the part that extends due to the tabs not filling up the area. I want this color to be the parent window's BG. Thanks
For the "content" of the tab, you would callEnableThemeDialogTexture(Visual Styles can have complex tab content backgrounds), for the area to the right of the actual tabs I think you might have to owner draw (TCS_OWNERDRAWFIXED style) unless just using the TCS_RIGHTJUSTIFY style is enough.
How can I set the backcolor of a control (equivilant of control.backcolor in .Net). I tried setBKColor with no luck. ex: TabHwnd = createWindowEx(NULL,WC_TAB.... then how could I set the back color of TabHwnd? Thanks
Windows will generate a message when it's painting the background of a control, and it is up to your program to respond to the message appropriately. WM_CTLCOLORBTNWM_CTLCOLOREDITWM_CTLCOLORDLGWM_CTLCOLORLISTBOXWM_CTLCOLORSCROLLBARWM_CTLCOLORSTATIC
From a standards standpoint, should I use the following from the C++<limits>header? UCHAR_MAXwhich is the c implementation orstd::numeric_limits<unsigned char>::max()which is the C++ implementation. The result is equivalent between the two versions but should I choose an implementation based on some standard or on readability and portability in this case. Note this implementation must be cross-platform compatible. I am writing C++ code.
If you want the code to be able to compile as C, then you pretty much need to use<limits.h>. If you're writing C++, it's probably better to use the C++<limits>header instead. The latter lets you write code that will work in templates that can't really be duplicated with the C header: ``` template <class T> class mytemplate { T x; void somefunc() { x = std::numeric_limits<T>::max(); } // or whatever... }; ```
I have a binary image in Matlab, and I need the binary array(0 and 1) in a C program, How can I import it? I can save the binary image in Matlab as ".mat" but I don't know how to read the mat file in C. Also I thought maybe I can save the binary image in Matlab as ".bin" which is readable in "C" but again I don't know how to save an image in matlab as ".bin". Any help would be greatly appreciated.
You can also write your data to a binary file, which will be about twice smaller then text. ``` img=rand(10)>.5; %# an array from @Amro's answer fid = fopen('test.bin','w'); fwrite(fid,img,'int8') fclose(fid); ``` Then I believe you can read it in C without problems. Remember, MATLAB will write data by columns, not by rows - first 1st column, then 2nd, etc. If you want to read it in C by rows, just transpose the array before writing: ``` fwrite(fid,img','int8') %# notice ' symbol after img ```
Is there any function or method to randomly choose a number (or 2 numbers or more) from an array?
Depending on how many numbers you need, the size of the array, and whether the array needs to retain its order, you could usestd::random_shuffleto reorder the array and then just loop from 0..n-1 to get n random numbers. This works better when you want to get a lot of numbers relative to the length of the array. If that doesn't seem appropriate, you can just usesrand()andrand() % nas an index into the array to get a pretty good approximation of a random selection.
I have the following lua script : ``` module("modoo",package.seeall) foo=1 bar={12,34} ``` Which works fine using the cli, such as : ``` > dofile "mod_modoo.lua" > =modoo.foo 1 > =modoo table: 0x86ce058 ``` As far as I understood, it works like a table, but whenever I try loading it as a table, a nil value is pushed onto the stack. Every other table works normally. I thought using lua_getglobal wouldn't work with modules, but I couldn't find the proper way to load it either ; how should I do it ?
Load Lua modules withrequirelikelua.cdoes. Seehttp://www.lua.org/source/5.1/lua.c.html#dolibrary
I am trying to get the size of PNG image (Without storing into file). I am usingthis codeas reference. When callingGetDIBits(), size of image would get updated intobi.biSizeImage. Everything works fine whenbi.biCompressionis BI_RGB. Then I have changed the compression mode from BI_RGB to BI_PNG;GetDIBits()started to fail. Please help me to solve this.
According tohttp://msdn.microsoft.com/en-us/library/dd145023%28VS.85%29.aspx: "This extension is not intended as a means to supply general JPEG and PNG decompression to applications, but rather to allow applications to send JPEG- and PNG-compressed images directly to printers having hardware support for JPEG and PNG images." using GetDIBits() with BI_PNG is not allowed.
``` struct inode_operations ext3_dir_inode_operations = { .create = ext3_create, .lookup = ext3_lookup, } ``` This struct is assign to inode structure and further to file system operation structure. My question is what is this flag.create? Do we do the assignment in the structure itself? Or is it some other version of C (C99, C89?) that allows this kind of operation? I hope my question is clear.
It's a C99 designated initialiser. It's equivalent to, in C89: ``` struct inode_operations ext3_dir_inode_operations = { 0 }; ext3_dir_inode_operations.create = ext3_create; ext3_dir_inode_operations.lookup = ext3_lookup; ```
What is the difference betweenunsigned longandUINT64? I think they are the same, but I'm not sure. The definition ofUINT64is : ``` typedef unsigned __int64 UINT64 ``` (by using StdAfx.h)
UINT64 is specific and declares your intent. You want a type that is an unsigned integer that is exactly 64 bits wide. That this may be equal to an unsigned long on some platforms is coincidence.
I would like to know if there is any way in which I can monitor a value of a variable until for example a counter reaches a value and then log the output of variable value during each counter value?
Set a watch point on the counter: ``` (gdb) watch var ``` And make that watchpoint conditional: ``` (gdb) cond <watchpoint_number> var>=value ``` If you want to log to a file: ``` (gdb) set logging file <filename> (gdb) set logging on ``` By default gdb logs to gdb.txt
I have installed linux 2.6. I wanted to know if there are any drivers to access the GPR port pins.
Look for a/dev/gpiofile.This linkshows some C code that accesses the GPIO pins. Please note that the exact way this works might differ with different ARM Linux distributions, and you don't give a lot of detail in your question.
Before I start building one myself; Is there a wrapper for C or C++ which does the same thing asSVNKit?
There is an API provided in C - see theSubversion Documentation
I'm using a Win32 Header. I want to make it so that the header item I click on stays 'selected' or looks selected until I press another one. I want to avoid disabling it for aesthetic reasons. Thanks
If this header is part of a listview, you can provide a visual clue withListView_SetSelectedColumn
i am going to read a TDMS file in matlab using Mexfunction in C language in a 64 bit windows machine, but i will develop the app in 32 bit windows machine. i know in there is a difference between 32 bit machine and 64 bits with the size of variables. i used a lot of fread(.. sizeof(type)..). is it going to be a problem when it is running in 64 bit machine? if so, how can i make it portable to 64 bits mahince? thanks
ISO C99 provides the header <stdint.h>, which defines, amongst others, types of the form intN_t and uintN_t, where N is the width of the corresponding integer or unsigned integer type. If an implementation provides integer types of width 8, 16, 32 or 64, it should provide the corresponding typedefs.
Where arepointersandglobal variablesstored inC? Are they saved in the memory, heap or stack?
Global variables can be in a couple places, depending on how they're set up - for example,constglobals may be in a read-only section of the executable. "Normal" globals are in a read-write section of the executable. They're not on the heap or the stack at all. Pointers are just a type of variable, so they can be wherever you want them to be (on the heap if youmalloc()them, on the stack if they're local variables, or in the data section if they're global).
Why are reference variables not present/used in C? Why are they designed for C++?
Because C was invented first. I don't know if they hadn't thought about references at the time (being mostly unnecessary), or if there was some particular reason not to include them (perhaps compiler complexity). They're certainly much more useful for object-oriented and generic constructs than the procedural style of C.
I am using CDT for developing C programs. When the debugger stops on a break point and I do "Step Over" or "Step Into" the debugger behaviour is based on the source line level but not on the instruction level. Can I do debugging on the instruction level in CDT?
In theDebugwindow (Debug perspective) there is anInstruction Stepping Modebutton: It looks like a small i with an arrowi=>).You can also set breakpoints on specific instructions in the Disassembly window.
Once again, GCC is making me feel like an idiot for having trouble with the simplest things. I've included a header: ``` #include "PDL.h" ``` Then, I try to compile: ``` arm-none-linux-gnueabi-gcc -I/cygdrive/c/PalmPDK/include -I../lua-5.1.4/lua-webos/include -O2 -Wall -shared -nostdlib -mcpu=arm1136jf-s -mfpu=vfp -mfloat-abi=softfp -lpdl ``` But it says: PDL.h: no such file or directory I can change into the include directory I specified above and see PDL.h is there, but GCC just doesn't see it.
/cygdrive is something specific to cygwin, so if gcc isn't compiled to use the cygwin unix emulation layer, it won't search it. Try using-IC:/PalmPDK/include.
I want to be able to know how much room a particular tab takes up, is there a way to calculate this knowing it's text and having its item struct? Thanks
Assuming a SysTabControl how aboutTCM_GETITEMRECT?
This question already has answers here:Closed13 years ago. Possible Duplicate:C pointer to array/array of pointers disambiguation In C, isint *thing[5]an array of five pointers, each pointing to an integer, or a pointer to an array of five integers?
[]trumps*per theC precedence tablewhich means you have an array of five int pointers.
This question already has answers here:Closed13 years ago. Possible Duplicates:what does malloc(0) return ?what’s the point in malloc(0)? Why does malloc(0) return valid memory address ? What's the use ?
If the size of the space requested is 0, the behavior is implementation-defined: the value returned shall be either a null pointer or a unique pointer. Source:mallocat The Open Group
is "register struct" legal? In terms of standards and (separated from standards) in Gcc?
Yes. (No citation, there is simply no prohibition on that. There is a note assuming that the use of register with arrays is valid, and arrays are far more second class citizen in C that structs).
Is there an easy way to read/write a nibble in a byte without using bit fields? I'll always need to read both nibbles, but will need to write each nibble individually. Thanks!
Use masks : ``` char byte; byte = (byte & 0xF0) | (nibble1 & 0xF); // write low quartet byte = (byte & 0x0F) | ((nibble2 & 0xF) << 4); // write high quartet ``` You may want to put this inside macros.
This question already has answers here:Closed13 years ago. Possible Duplicate:what is the difference between const int*, const int * const, int const * ``` Are there any Difference between const char* p and char const* p ```
const char* pis a pointer to aconst char. char const* pis a pointer to achar const. Sinceconst charandchar constis the same, it's the same. However, consider: char * const pis aconstpointer to a (non-const) char. I.e. you can change the actual char, but not the pointer pointing to it.
I am trying to write a very small SNMP trap receiver, listening to UDP port 162. Traps come in fine, but I can not decode them. I have found libber, but it can't decode the traps for some reason. I am probably using it wrong. I imagine decoding an SNMP trap should be fairly simple and that I am missing something crucial. Is it possible to use NET-SNMP as a library and create a small trap-receiving program from it? I would not be surprised at all, but can not find any information about it. Maybe my google-fu is weak.
Well, using net-snmp, you usually use snmptrapd daemon that calls for you external commands/scripts. If you cannot use this way, I suggest you look at snmptrapd.c code. Moreover, if I recall correctly, they build a libsnmptrapd library. It should be easy to find the right API calls ... If I have time I will update my answer with a snippet ... my2c
I am currently developing a programming language in C, and I want to allow users to create apparently "unlimited" arrays with numerical indices without sacrificing performance in the process. For example,table [1000000000]would ideally be creatable and accessible in an instant without the memory overhead of a table of 1,000,000,000 items, 999,999,999 of which were unused; but the array would also perform well whentable [n]was defined for, say, 1 ≤ n ≤ 1000000. Do you have suggestions for the implementation of such an array-handling system?
There's Judy Arrayshttp://judy.sourceforge.net/
I have UTC time which is coming from UDP, I have a program to calculate Day and Time of UTC, how can I set my system clock at that day and time, kindly give me some direction so that I can make it possible. I am using Window OS.
To set the current system time, use theSetSystemTimeWin32 API function.
In C, what will happen if I supply a signed integer especifically a negative integer as the 3rd argument to the memcpy function? Example: ``` memcpy(destBuf, source, -100*sizeof(source)) ``` Will the result of-100*sizeof(source)be interpreted by memcpy as unsigned? Thanks!
the last parameter is unsigned. so by doing -100 * sizeof( source ) you'll get a huge number (That will wrap around, ie overflow). This is equivalent to doing "4,294,967,196 * sizeof( source )". Edit: Actually thats wrong I just realised. It will do -100 * sizeof( source ) and then convert it to an unsigned. For example if sizeof( source ) is 4 then it will convert -400 to unsigned and give you 0xFFFFFE70 (4,294,966,896).
As documented: "If not all tabs can be shown at once, the tab control displays an up-down control so that the user can scroll additional tabs into view." http://msdn.microsoft.com/en-us/library/bb760550%28VS.85%29.aspx I don't want this. I don't want an up down control to show if I have too many and I don't want multiline tabs. I want a single strip. I will handle the case of too many tabs with a control I create myself, but I don't want the up-down control. Thanks
There's no style for that, so i believe the only way is a bit of hacking. From what i can see with my Spy++, the updown control is a true child control of the tab control with id = 1. So, you can actually hide it with ShowWindow().
I am using C language and Linux as my programming platform in embedded device. My question is, how to correctly retrieve the current processor time(tick). I am using clock() function in time.h and it seems I am getting inconsistent value. Thanks.
Theclock()function measures the CPU time consumed by your process. It doesn't increment while your process is sleeping or blocked. If you want a high resolution clock that advances continually, useclock_gettime(CLOCK_MONOTONIC, ..).
Is there a way for windows created with WS_CHILD to inherit the parent's background color rather than default to Dialog Color? I'm trying to do this for a tab control, mainly the part that extends due to the tabs not filling up the area. I want this color to be the parent window's BG. Thanks
For the "content" of the tab, you would callEnableThemeDialogTexture(Visual Styles can have complex tab content backgrounds), for the area to the right of the actual tabs I think you might have to owner draw (TCS_OWNERDRAWFIXED style) unless just using the TCS_RIGHTJUSTIFY style is enough.
How can I set the backcolor of a control (equivilant of control.backcolor in .Net). I tried setBKColor with no luck. ex: TabHwnd = createWindowEx(NULL,WC_TAB.... then how could I set the back color of TabHwnd? Thanks
Windows will generate a message when it's painting the background of a control, and it is up to your program to respond to the message appropriately. WM_CTLCOLORBTNWM_CTLCOLOREDITWM_CTLCOLORDLGWM_CTLCOLORLISTBOXWM_CTLCOLORSCROLLBARWM_CTLCOLORSTATIC
What is the difference betweenunsigned longandUINT64? I think they are the same, but I'm not sure. The definition ofUINT64is : ``` typedef unsigned __int64 UINT64 ``` (by using StdAfx.h)
UINT64 is specific and declares your intent. You want a type that is an unsigned integer that is exactly 64 bits wide. That this may be equal to an unsigned long on some platforms is coincidence.
I would like to know if there is any way in which I can monitor a value of a variable until for example a counter reaches a value and then log the output of variable value during each counter value?
Set a watch point on the counter: ``` (gdb) watch var ``` And make that watchpoint conditional: ``` (gdb) cond <watchpoint_number> var>=value ``` If you want to log to a file: ``` (gdb) set logging file <filename> (gdb) set logging on ``` By default gdb logs to gdb.txt
I have installed linux 2.6. I wanted to know if there are any drivers to access the GPR port pins.
Look for a/dev/gpiofile.This linkshows some C code that accesses the GPIO pins. Please note that the exact way this works might differ with different ARM Linux distributions, and you don't give a lot of detail in your question.
In .Net there is something called a menu strip. These are more customizable than HMENU's. How could I create one of these in unmanaged C++? Thanks
They aren't more customizable than HMENUs, they're justeasierto customize. If you don't want to useMFC C++ WinAPI wrapper, what do you want to customize ?
I am using C language and Linux as my programming platform. In my app, I call pthread_create. Then I check the memory usage of my app using ps commandline tool and it adds 4 in the VSZ column. But the problem is when the pthread_create function handler exits, the 4 that was added in the memory was not release. Then when the app call the pthread_create again, a 4 value was added again until it gets bigger. I tried pthread_join and it seems the memory still getting bigger. Thanks.
psis not the right tool to measure memory leaks. When you free memory, you are not guaranteed to decrease the process' vsize, both due to memory fragmentation and to avoid unnecessary system calls. valgrindis a better tool to use.
I want to find most often seen string in a huge log file. Can someone help me how to do this. one way to do this is to hash each and every string and count the maximum value but its not efficient. Are there any better ways to do this. Thanks & Regards, Mousey.
If by string you mean line, then on any unix-like shell you should be able to do something like: ``` sort logfile.txt | uniq -c ``` This presumes that you do not have something actually unique on each line - like a timestamp, and that the file is small enough to be reasonably treated in this way. Of course this does not use C or C++ "directly", but given that the tools themselves are likely coded in one of them then it should count :-)
I'd like the following code to work: ``` double num = 31415; /* num will never have a decimal part */ /* ... code here so that we can now say */ printf("%d", num_array[0] == 3 && num_array[1] == 1 && num_array[4] == 5); //1 ``` I realize it's trivial to do this with ints (justint i=0; while(num>0) numarr[size-++i] = num%10, num/=10;where size is predetermined to be the number of digits in the number), but that obviously won't work for floats/doubles because you can't mod one floats. And yes, I need to use floats/doubles, despite not using the floating point section (it's an exercise). And I have figured out how to determine the number of digits in a double, using floor(). ``` /* n > 0, n=floor(n) */ int numdigits(double n){ int i = 0; while (n >0) n = floor(n/10), i++; return i; } ```
Look upfmod. The number of digits will probably be easier to compute usinglog10.
I was just skimming the C99 standard, looking for something that I don't remember now, when I noticed that the pointer returned from thestrerror()function (section 7.12.6.2) isn't const-qualified, even though the standard says: The strerror function returns a pointer to the string, the contents of which arelocale-specific.The array pointed to shall not be modified by the program,but may be overwritten by a subsequent call to the strerror function. Is there an obvious reason for this function to return a modifiable string instead of something like: ``` char const * const strerror(int errnum); ``` or at the very least ``` char const * strerror(int errnum); ```
Same as for the type of string literals: It was already like that in C89, describing a practice dating back to before the introduction ofconstin the language. Changing it would make current valid program invalid.
Assume we have an integer 'x' and 'n' possible values that 'x' can be mapped/binned to. What is an elegant way in C to have a function that returns the closest 'nth' value to x? Pseudo code example; ``` int x = 40; int res; int bins[] = { 0, 20, 80, 200 }; /* Sorting is guaranteed */ res = int_bin(x, bins); assert(res == 20); /* 40 is closer to 20 than 80 */ x = 150; res = int_bin(x, bins); assert(res == 200); /* 150 is closer to 200 than 80 */ ``` By elegant I mean not just a bunch of if/else if/else statements.
If the list is sorted, then you can simply do a binary search for the value. If the search does not find the value in the list, you will know at what index the value would have been located had it been in the list. Then, you can then compare the value against the element at that index and the element at the previous index (if the index isn't zero, obviously) and see which is closer.
Are these 2 methods equivalent ? ``` char a[10] = ""; char a[10] = { 0 }; ``` Also, I would like to declare-initialize a struct but this will not work in gcc: ``` struct c { char d[10]; int e; }; struct c f = { 0 }; ``` a.c: In function ‘main’:a.c:33: warning: missing braces around initializera.c:33: warning: (near initialization for ‘f.d’)a.c:33: warning: missing initializera.c:33: warning: (near initialization for ‘f.e’)a.c:33: warning: unused variable ‘f’
Yes, the two char[] initialisations are identical - both will initialise the array to contain zeros. For the structure problem, try: ``` struct c f = { {0}, 0 }; ``` (With newer versions of gcc that support C99 you can alsoname the elements of the structure being initialised.)
How can I get Visual Studio to help me optimize my application, or tell me areas of slowness? Thanks
If you have Visual Studio 2013 Professional then you can use the Performance and Diagnostics hub:http://blogs.msdn.com/b/visualstudioalm/archive/2013/07/12/performance-and-diagnostics-hub-in-visual-studio-2013.aspx. This profiler is well integrated in the IDE and I've found it really quick and easy for spotting code hotspots.
foo.c: ``` struct foo { int a; }; ``` bar.c: ``` struct foo { char *s; double x,y; }; ``` Thestructdefinitions are only in .c files. Is it legal according to C standard? Which part of standard says so? (There is no #inclusion ofstructdefinitions.)
The code is perfectly legal C. You might run into problems with debuggers (mistaking one type for another and attempting to display one as another), but it is fine from the language point of view. There's no part of the standard that would directly say that this is legal. Rather, there's no part of the standard that says it is illegal. Something like this would be illegal in C++, since C++ extends the concept oflinkageto classes and non-local in C++ classes always have external linkage.
I'm currently in the process of writing a CGI blog engine in C (fun project - don't hate! :) and I'd like to enable posting for every user that has a login on the machine the webserver is running on. What is the correct way to see if a supplied login and password match against the systems login data? Just to clarify, if I have a shell login "user" with password "pass" on the host machine, I'd like to be able to authorize myself with the same "user" and "pass" on the CGI page. Disclaimer:I know that sending your shell login data unencrypted over possibly multiple routers to a CGI site is as secure as trying to make fire inside a filled gas-tank, but this is (and remains) a localized fun project :)
You'll need libshadow to do you authentication. There's a convenient overview here. http://www.linux.org/docs/ldp/howto/Shadow-Password-HOWTO-8.html
I have two large framework libraries, whose header files are included in my project. Either one works flawlessly, but including both causes erratic behaviour (but no error message related to the macro). I assume that they both #define a macro of the same name. What is the most efficient way to identify the problematic macro?
I assume that they both #define a macro of the same name. That should generate at least a warning by the compiler (if they are in the same translation unit). How do I identify redefined macros in C/C++? As far as I know there is no straight-forward way. Either one works flawlessly, but including both causes erratic behaviour Can you please give us some details on the eratic behaviour? What actually happens? What makes you think it's the macro definitions?
Assume we have an integer 'x' and 'n' possible values that 'x' can be mapped/binned to. What is an elegant way in C to have a function that returns the closest 'nth' value to x? Pseudo code example; ``` int x = 40; int res; int bins[] = { 0, 20, 80, 200 }; /* Sorting is guaranteed */ res = int_bin(x, bins); assert(res == 20); /* 40 is closer to 20 than 80 */ x = 150; res = int_bin(x, bins); assert(res == 200); /* 150 is closer to 200 than 80 */ ``` By elegant I mean not just a bunch of if/else if/else statements.
If the list is sorted, then you can simply do a binary search for the value. If the search does not find the value in the list, you will know at what index the value would have been located had it been in the list. Then, you can then compare the value against the element at that index and the element at the previous index (if the index isn't zero, obviously) and see which is closer.
Are these 2 methods equivalent ? ``` char a[10] = ""; char a[10] = { 0 }; ``` Also, I would like to declare-initialize a struct but this will not work in gcc: ``` struct c { char d[10]; int e; }; struct c f = { 0 }; ``` a.c: In function ‘main’:a.c:33: warning: missing braces around initializera.c:33: warning: (near initialization for ‘f.d’)a.c:33: warning: missing initializera.c:33: warning: (near initialization for ‘f.e’)a.c:33: warning: unused variable ‘f’
Yes, the two char[] initialisations are identical - both will initialise the array to contain zeros. For the structure problem, try: ``` struct c f = { {0}, 0 }; ``` (With newer versions of gcc that support C99 you can alsoname the elements of the structure being initialised.)
How can I get Visual Studio to help me optimize my application, or tell me areas of slowness? Thanks
If you have Visual Studio 2013 Professional then you can use the Performance and Diagnostics hub:http://blogs.msdn.com/b/visualstudioalm/archive/2013/07/12/performance-and-diagnostics-hub-in-visual-studio-2013.aspx. This profiler is well integrated in the IDE and I've found it really quick and easy for spotting code hotspots.
foo.c: ``` struct foo { int a; }; ``` bar.c: ``` struct foo { char *s; double x,y; }; ``` Thestructdefinitions are only in .c files. Is it legal according to C standard? Which part of standard says so? (There is no #inclusion ofstructdefinitions.)
The code is perfectly legal C. You might run into problems with debuggers (mistaking one type for another and attempting to display one as another), but it is fine from the language point of view. There's no part of the standard that would directly say that this is legal. Rather, there's no part of the standard that says it is illegal. Something like this would be illegal in C++, since C++ extends the concept oflinkageto classes and non-local in C++ classes always have external linkage.
I'm currently in the process of writing a CGI blog engine in C (fun project - don't hate! :) and I'd like to enable posting for every user that has a login on the machine the webserver is running on. What is the correct way to see if a supplied login and password match against the systems login data? Just to clarify, if I have a shell login "user" with password "pass" on the host machine, I'd like to be able to authorize myself with the same "user" and "pass" on the CGI page. Disclaimer:I know that sending your shell login data unencrypted over possibly multiple routers to a CGI site is as secure as trying to make fire inside a filled gas-tank, but this is (and remains) a localized fun project :)
You'll need libshadow to do you authentication. There's a convenient overview here. http://www.linux.org/docs/ldp/howto/Shadow-Password-HOWTO-8.html
I have two large framework libraries, whose header files are included in my project. Either one works flawlessly, but including both causes erratic behaviour (but no error message related to the macro). I assume that they both #define a macro of the same name. What is the most efficient way to identify the problematic macro?
I assume that they both #define a macro of the same name. That should generate at least a warning by the compiler (if they are in the same translation unit). How do I identify redefined macros in C/C++? As far as I know there is no straight-forward way. Either one works flawlessly, but including both causes erratic behaviour Can you please give us some details on the eratic behaviour? What actually happens? What makes you think it's the macro definitions?
I need to find the duration of numerous formats of audio and video files, in milliseconds. I've been searching around for a while, but I can't find anything that will let me do this. I'm using C/++ in Linux. Thanks in advance.
There is aMediaInfoSourceFourge project that shows this info. You can look in its code for that.
``` #include <stdio.h> #include <Windows.h> int main() { TCHAR buff[1024]; GetLogicalDriveStrings(1024, buff); int i; for(i = 0; buff[i] != 0; i += 4) printf("%S", buff+i); } ``` When I try to compile it with MSVC, I get the following errors: http://ahb.me/5T- Commenting outGetLogicalDriveStrings(1024, buff);causes the code to compile just fine
Older version of C require local variables to be declared at the beginning of a block, before things like function calls. Move theint i;to the top of the function to be with the declaration ofbuff. C++ did away with this requirement, as did C99.
I think this maybe a really dumb question, but i just want to be clarified. Thanks in advance! I'm not sure if an array of structure declared as a local variable inside a function gets allocated in the stack. Doesn't?
It does; anything you declare without allocating yourself (e.g. by callingmalloc) or declare static (asFernando says) is allocated on the stack. Structures are just a way of grouping together multiple variables; they still have a fixed size (the total size of their elements, possibly plus some padding), and accessing a struct's field just means pulling the appropriate bytes from somewhere within the struct
Is there a way to make a toolbar button look different than the rest (Aside from changing bitmap or setting its state to Disable? Is there away to make it look highlighted all the time? I want the selected tool to look selected. Thanks (Sort of like the way open applications are "Selected" in Windows 7.
Send the TB_SETHOTITEM message
Given two arraysA[n]andB[m], how can I find the smallest window inAthat contains all the elements ofB. I am trying to solve this problem in O(n) time but I am having problem doing it. Is there any well know algorithm or procedure for solving it.
Ifm > n,Acannot contain all the elements ofB(and hence we have anO(1)solution). Otherwise: Create a hash table mapping elements ofBto the sequence {0..m-1} (this isO(n)sincem <= n) .Create an arrayC[m]to count occurences of the members ofB(initialise to 0) in the current window.Create a variablezto count the the number of 0 elements ofC(initialise tom).Create variablessandeto denote the start and end of the current windowwhilee < n:Ifzis nonzero, incrementeand updateCandz.O(1)else consider this window as a possible solution (i.e. if it's the min so far, store it), then incrementsand updateCandz.O(1) The while loop can be shown to have no more than2niterations. So the whole thing isO(n), I think.
If i have an array of coordinates for a path(Such as in a paint program), what is the best way to render the entire path with SDL? I looked at setting pixels individually, but from what i've seen that's a bad idea. I also thought about drawing all the coordinates as SDL_Rect's, but rendering a large list of rect's each frame sounds slow. Is there a simple way of achieving this effect?
You can implement yourself theBresenham line algorithmdirectly accessing the framebuffer but I think you'll be doing much better using OpenGL...
I wanted to know a way to find out what the disk's block size is through a function or a compiler constant in C.
The info about you using gcc compiler is not interesting, since compilers are not interested in the block size of the filesystem, they are not even aware of the fact that a filesystem can exist... the answer is system specific (MS Windows? GNU/Linux or other *nix/*nix like OS?); on POSIX you have thestatfunction, you can use it to have the stat struct, which contains the fieldst_blksize(blocksize for filesystem I/O) which could be what you're interested in. ADD Example ``` #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdio.h> int main() { struct stat fi; stat("/", &fi); printf("%d\n", fi.st_blksize); return 0; } ``` Tells you about the filesystem used on / (root); e.g. for me, it outputs 4096.
Can I use a forloop to get the property names of a "struct" in C? Or would I just have make a separate list? (Just the name I am looking for)
You'll have to make a separate list. The C programming language doesn't have any introspection capabilities that would let you enumerate the property names of a struct.
When a menu item or context menu is made, it has a shadow, if I create a window with WS_POPUP instead of WS_CHILD it has no shadow. How can I get the shadow? Thanks
It is enabled with WNDCLASSEX.style. Turn on theCS_DROPSHADOW style. I think this only works on top-level windows.
I notice Vista/7 uses this type of control as well as Windows Live Messenger. This is the control: How can this control be programably added to a WinAPI application? Thanks
This resource is Bitmap 7016 in explorer.exe's resources. It is a 32 bit bitmap, so it has an extra alpha channel. This is how it is done.
AreStatement and Declarations in Expressionsspecific to GNU C ? Or this feature is also included in C99 standard ?
It's a GCC extension. (See the GCC docs,e.g. here for gcc 4.3.3, for a full list of GCC extensions; and theC99 spec is available here.) GCC will warn about such things if you use the-pedantic -std=c99flags, e.g.: ``` $ cat foo.c int main(void) { return ({ int a = 0; a; }); } $ gcc -pedantic -std=c99 -c foo.c foo.c: In function 'main': foo.c:3: warning: ISO C forbids braced-groups within expressions ```
What will be solution in the following code ``` Class A{} void func(){} printf("%d,%d",sizeof(A),sizeof(func)); ```
Size of an empty class is non zero(most probably 1), so as to have two objects of the class at different addresses. http://www2.research.att.com/~bs/bs_faq2.html#sizeof-emptyexplains it better ``` class A{}; void func(){} std::cout<<sizeof(A)<<std::endl<<sizeof(&func));// prints 1 and 4 on my 32 bit system ```
I'm wondering what the stencil buffer is and what it can do.
http://en.wikipedia.org/wiki/Stencil_buffer Basically, the stencil buffers allows you to draw only in parts "marked" in the stencil buffer, rejecting pixels where this "mark" doesn't have certain value. Is used to clip rendering in non-rectangular shapes, and to doshadow volumes.
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.Closed13 years ago. Recently I was debugging a project and the debugger (GDB 7.1) crashed all of a sudden, because of an endless recursion while trying to print a graph structure. At first I couldn't even imagine that a debugger could crash (a stable version) but it had. So it's really interesting to me, have you ever crashed a debugger?
Yes​​​​​​​​​​​.
I know this is an OS function. But is there a way of increasing your overall stack or heap size through C? sbrk() is used to change the size of data segment right? Does this imply both stack and heap?
You mentionedsbrk(), so I'm going to assume you mean Unix/Linux. sbrk() will change the size of the data segment, but usually the stack is in a different memory space than the data segment, to keep people from overwriting the stack and doing evil things. Typically you'll set your stack size before you start the program running by usingulimitfrom your shell. Note: sbrk() is deprecated in favor ofmalloc(). The Open Unix specification defines (and Linux implements) thegetrlimit()andsetrlimit()functions, which also allow you to play with system limits.
In C I have a pointer that is declared volatile and initialized null. ``` void* volatile pvoid; ``` Thread 1 is occasionally reading the pointer value to check if it is non-null. Thread 1 will not set the value of the pointer. Thread 2 will set the value of a pointer just once. I believe I can get away without using a mutex or condition variable.Is there any reason thread 1 will read a corrupted value or thread 2 will write a corrupted value?
To make it thread safe, you have to make atomic reads/writes to the variable, it being volatile is not safe in all timing situations. Under Win32 there are the Interlocked functions, under Linux you canbuild it yourself with assemblyif you do not want to use the heavy weight mutexes and conditional variables. If you are not against GPL thenhttp://www.threadingbuildingblocks.organd itsatomic<>template seems promising. The lib is cross platform.
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 answered with facts and citations.Closed8 years ago.Improve this question I want to add a toolbar and know which tool was clicked. I'd also like to be able to change the toolbar's buttons' bitmap after theyve been created MSDN is fairly breif on all of this. Thanks
If you like to learn by example then you may find this code useful. It's a Windows toolbar wrapper class I created some time ago. It's somewhat advanced though because it uses Custom Draw. WindowsToolbar.hWindowsToolbar.cppWindowsToolbarItem.hWindowsToolbarItem.cpp
AreStatement and Declarations in Expressionsspecific to GNU C ? Or this feature is also included in C99 standard ?
It's a GCC extension. (See the GCC docs,e.g. here for gcc 4.3.3, for a full list of GCC extensions; and theC99 spec is available here.) GCC will warn about such things if you use the-pedantic -std=c99flags, e.g.: ``` $ cat foo.c int main(void) { return ({ int a = 0; a; }); } $ gcc -pedantic -std=c99 -c foo.c foo.c: In function 'main': foo.c:3: warning: ISO C forbids braced-groups within expressions ```
What will be solution in the following code ``` Class A{} void func(){} printf("%d,%d",sizeof(A),sizeof(func)); ```
Size of an empty class is non zero(most probably 1), so as to have two objects of the class at different addresses. http://www2.research.att.com/~bs/bs_faq2.html#sizeof-emptyexplains it better ``` class A{}; void func(){} std::cout<<sizeof(A)<<std::endl<<sizeof(&func));// prints 1 and 4 on my 32 bit system ```
I'm wondering what the stencil buffer is and what it can do.
http://en.wikipedia.org/wiki/Stencil_buffer Basically, the stencil buffers allows you to draw only in parts "marked" in the stencil buffer, rejecting pixels where this "mark" doesn't have certain value. Is used to clip rendering in non-rectangular shapes, and to doshadow volumes.
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.Closed13 years ago. Recently I was debugging a project and the debugger (GDB 7.1) crashed all of a sudden, because of an endless recursion while trying to print a graph structure. At first I couldn't even imagine that a debugger could crash (a stable version) but it had. So it's really interesting to me, have you ever crashed a debugger?
Yes​​​​​​​​​​​.
I know this is an OS function. But is there a way of increasing your overall stack or heap size through C? sbrk() is used to change the size of data segment right? Does this imply both stack and heap?
You mentionedsbrk(), so I'm going to assume you mean Unix/Linux. sbrk() will change the size of the data segment, but usually the stack is in a different memory space than the data segment, to keep people from overwriting the stack and doing evil things. Typically you'll set your stack size before you start the program running by usingulimitfrom your shell. Note: sbrk() is deprecated in favor ofmalloc(). The Open Unix specification defines (and Linux implements) thegetrlimit()andsetrlimit()functions, which also allow you to play with system limits.