question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
This question already has answers here:Closed11 years ago.
Possible Duplicate:getting segmentation fault in a small c program
Here's my code:
```
char *const p1 = "john";
p1[2] = 'z'; //crashes
printf("%s\n", p1);
```
I know p1 is a "read-only" variable, but I thought I could still modify the string ("john" ). ... |
You cannot safely modify string literals, even if the pointer doesn't lookconst. They will often be allocated in read-only memory, hence your crashes - and when they're not in read-only memory modifying them can have unexpected consequences.
If you copy to an array this should work:
```
char tmp[] = "john";
char *co... |
i wrote a small prog :
```
1 #include<stdio.h>
2 main(){
3 char* str = "string";
4 *str = 'k';
5 printf("string is = %s\n",str);
6 }
```
This program gets compiled without any error or warnings, but when i run it, it gives segmentation fault. While if i rewrite the 3rd line ... |
```
char* str = "string";
```
This puts the string in read-only memory. It is undefined behavior (usually unpleasant behavior) when you try to modify it with the next line. Try something like
```
char str[] = "string";
```
instead.
|
Consider the following C function.Does opening the braces to create a local scope make compilers create a record on the stack to mantain the variables declared in the scope ?
```
void function()
{
int q,r;
...
{
int i = 0;
int j = 3;
q = j + 1;
}
...
}
```
If so... |
The arrangement of the stack is not specified by the C standard.
Curly braces ({}) introduce a new scope, so in principle, yes, this could create a new frame on the stack. But the compiler may choose to optimise this overhead away.
|
I am programming an AVR microcontroller, and in the programmers notepad in the WINAVR Suite.
I am trying to seperate my code, however the sepeaet .c file I am unable to use AVR pre-defined variables. (the variables AVR supplies to point to certain BITs)
for example,
this code will work in my main.c file. but not in ... |
You have to includeavr/io.hin your projet and also specify the mcu in thegcccompiler command line with-mmcu=option.
|
Is the concept of the Fortran ISO_C_BINDING module also supported by C/C++ compiler vendors? For example, the size of a C/C++intcan vary between the compilers from different vendors. So, with the ISO_C_BINDING module, we know that a FortranC_INTtype is 4 bytes; rather than merely having akindof 4. But, we still don't ... |
As far as I know, the standard only demands matching types in the same toolchain. Thus you are better using the C-Compiler from the same vendor. The standard doesn't claim anything about the sizes of the C_ kinds, I think.
Edit: Just looked it up in the standard, it is always talking about the companion C-compiler.
|
I have implemented a chat server in C/Linux that uses TCP sockets. It is currently using a single process and uses select() to keep the server from blocking. I've read that select() is a pretty slow method and I'm looking to upgrade the server to a more efficient version.
I'm currently looking at libevent but I was h... |
For Linux (only) you can use epoll, which is faster in most cases (but not all).
The main disadvantage of epoll is that it is supported on the Linux OS only (not portable).
In a summary note, epoll can monitor a very large number of descriptors and will return a list ofonlythose that changed (no need to pass over al... |
I want to build a string label with a changing suffix. This is to take place within a for-loop. (The suffix being the value that is looped through). This is how I'd do it in C - is there a more c++-ish way to do this?
```
for (int i = 0; i<10; i++)
{
char label[256];
sprintf(label, "Label_no_%d", i);
//... |
You can use stringstreams:
```
for (int i = 0; i<10; i++)
{
std::ostringstream label;
label << "Label_no_" << i;
// use label.str() to get the string it built
}
```
These let you useoperator<<, exactly like you would forstd::coutor a file, but writing to an in memory string instead.
Or alternatively y... |
I've declared the following array of strings:
char *arrayIndices[100] = {0};
I do a comparison with recp->ut_line which is declared as:
```
struct utmp {
....
char ut_line[32]
}
```
using:
```
strcmp(arrayIndices[i], (char*)recp->ut_line))
```
This gives me a segmentation error.
I've also tried these in gdb:
```... |
You need to use apostrophes, not quotes, here:
if (arrayIndices[i] == '\0')
|
If I have an objectatype objwhereatypeis defined liketypedef struct myType {...} * atype, is there any way I can get all the references toobj, or at least how many there are?
Something like:
```
atype obj;
... // Allocate
aStruct a;
a.obj = obj;
aStruct b;
b.obj = obj;
int refs = get_references(obj); // refs shou... |
No, there's no implicit way. But you could implement areffunction that automatically increases a counter, and anunreffunction to decrement it.
```
a.obj = ref(obj);
/* ... */
a.obj = something_else;
unref(obj);
```
And that counter can be something external to any of thestructs. For example, you could use a hash ta... |
I Created a toolbar resource (IDR_TOOLBAR) using resource editor, how can I add it to a window using basic Win32 APIs?
|
There is no "Toolbar resource" thing for WIN32 API.
Toolbar resources are artifacts for MFC classes likeCToolbarand the like.
It actually consist in a bitmap (contaning the stripe of the images, and having the same ID of the toolbar) and aRT_TOOLBAR(actuallyMAKEINTRESOURCE(241)) resource type that is a linear vector ... |
I keep getting this error mesage when trying to add a breakpoint in gdb.
I've used these commands to compile:
```
gcc -g main.c utmpib2.c -o main.o
and:
cc -g main.c utmpib2.c -o main.o
and also:
g++ -g main.c utmpib2.c -o main.o
```
I also tried "-ggdb" instead of "-g" and I still get that error message.
I then e... |
You have to add extra parameter -g, which generates source level debug information. It will look like:
```
gcc -g prog.c
```
After that you can use gdb in common way.
|
I am working with a Hashtable struct that maps keys to values, where the values are (void *) so that Hashtables can hold any kind of value.
To be able to free those values, the deconstructor of a Hashtable takes in a pointer to a freeing function as an argument. In my case, I know I am going to be freeing basic types... |
You can (and should) pass tofreeevery pointer that has returned bymalloc, no matter which type (or struct) it points to. Be careful tonotpass tofreepointers that you didn't get from malloc. (Middle of arrays, local variables, etc)
BTW, unless some of your data types need some work before freeing, you can do it withou... |
I'm using distutils, and have a module spammodule.c that compiles,links and works perfectly.
But if I rename that module to .cpp and re-run the distutils build/install sequence, the module builds but gives me an error on import in python:
ImportError: dynamic module does not define init function (initspam)
Is there... |
You need to enclose your init function within
```
#ifdef __cplusplus
extern "C" {
#endif
//initspam goes here
#ifdef __cplusplus
}
#endif
```
in order to prevent its name from getting mangled.
|
I need to get the date as one string and the current time as another in C. I've had a look at time.h and see it allows me to get the whole thing. Do I then have to use some string methods? I notice that C doesn't have a substring method? Strcpy seems like it might work but I need a char * not an array.
Any advice?
T... |
You can usestrftimefor this:
```
struct tm *tm;
time_t t;
char str_time[100];
char str_date[100];
t = time(NULL);
tm = localtime(&t);
strftime(str_time, sizeof(str_time), "%H %M %S", tm);
strftime(str_date, sizeof(str_date), "%d %m %Y", tm);
```
|
I am building a small OS. For that i wanted to play audio. I can use ports,interrupts. I haveno restrictions as i am building an OSitself.
Sohow can i play an audio file using a C program. Please remember that I cannot and don't want to use any ready made library or so.
|
If you're building your own OS, you also need to care about the physical details of your audio hardware.
Differences in hardware is why operating systems introduced the concept of the device driver.
If your audio hardware is sound blaster compatible, have a look here:
http://www.phatcode.net/res/243/files/sbhwpg.pd... |
I am trying to use a double pointer to a structure. The build is successful, but on running, it gives the following error:
Run-Time Check Failure #3 - The variable 'test2' is being used without being initialized.
The code is:
```
testStructure* test1 = (testStructure*)malloc(sizeof(testStructure));
testStructure** ... |
```
*test2 = test1; // test2 is pointing no where to get dereferenced.
```
must be
```
test2 = &test1;
```
|
Similar to how python has the convenientos.path.join()function, I was wondering if there was a good cross-platform way to do this in C.
My current approach is to set up some preprocessor directives with something like this
```
#ifdef defined(linux)
#define PATH_SEPARATOR "/"
#else
#define PATH_SEPARATOR "\\"
#endif
... |
I'm pretty sure many cross-platform libraries have such functionality. Maybe you want to have a look at APR'sapr_filepath_mergefunction.
In C++, you could use Boost:
```
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
[...]
path path1("/tmp");
path path2("example");
path result = path1 / pat... |
The standard C assert macro is disabled when the macroNDEBUGis defined, meaning "Not debug". This leads to really awful double negative cases like#ifndef NDEBUG //DebuggingCode #endif. It seems like RELEASE would have been a better choice of terms, but I can't believe the standards committee would have done it that wa... |
The macroNDEBUGcontrols howassertbehave.
You should typically NOT use it for anything else. If you would use it for other things, like extra debug trace output, you don't have the option to build your application without this extra code but with assertions enabled.
I would recommend that you define your own preproce... |
I'm curious why__builtin_return_address()doesn't supports other arguments than 0 in ARM ?
It's a problem that somehow you can't deduce calling function address from the stack of ARM ?
Or something else ?
Thanks
|
According to this post <http://codingrelic.geekhold.com/2009/05/pre-mortem-backtracing.html>,
Also on some architectures, including my beloved MIPS, only__builtin_return_address(0)works. MIPS has no frame pointer, making it difficult to walk back up the stack. Frame 0 can use the return address register directly.
I... |
```
static int a[] = {1, 5, 645, 43, 4, 65, 5408, 4, 7, 90, 23, 11};
int len=sizeof(a)/sizeof(int);
```
Is there a shortcut, with ANSI 99?
|
I think that there isn't a shortcut, but you cat use macro:
```
#define arrlen(arr) (sizeof(arr)/sizeof(arr[0]))
```
|
I want to know how to check existence and read files (may be with C linux kernel functions) /proc/mtd and /proc/partitions in my program developped in C (for OpenWrt), without using fopen,fread,... functions?
thanks in advance for your help
|
To determine whether a file exists you could try getting the file's stats (creation time, protections, etc.). That would not require you to open or read the file's contents. The error code would tell you whether you simply didn't have permission to perform the action or whether the file didn't exist.
As for reading... |
I am receiving 2 bytes of binary information via Serial in C.
I am receiving them in a char.
So I need to join the 2 chars to make a int but Im unsure how to do that.. first of all the first byte is in binary format and not char format.. So im unsure how I Can convert it into a useable form for my program.
|
JustORthem together ?
```
x = (b1 << 8) | b2;
```
Make sure they're unsigned or cast accordingly (shifting signed stuff is nasty).
|
I am learning NASM as I write bootloaders. So far I have a hello world bootloader. I want to know how to link a c program to it and have the bootloader load it into memory and start executing it's entry point function. I need NASM code as I am a NASM n00b. Thank you very much for you help.
EDIT: Basically I need to k... |
Althoughthis tutorialis for C++, its the exact same procedure (the tutorial lists the parts that are C++ specific, which are just the static ctors & dtors).
when ever your are having problems in this area,osdev.orggenerally has the answer or a tutorial
|
I am writing a program in C with switch statements and I was wondering if the compiler will accept a statement such as
```
case !('a'):
```
I couldn't find any programs online that used the!with a switch statement.
|
Did you actually try it?
Well, I did (gcc on Mac OS X).
! is the logical negation operator, and !(x) returns 1 for an x of 0, and 0 for anything else.'a'has a value which is known at compile-time, so the compiler evaluates!('a')to 0. So
```
case !('a'):
```
is the equivalent of
```
case 0 :
```
It doesn't even g... |
how would you get the last word of a string, starting from the '\0' newline character to the rightmost space? For example, I could have something like this where str could be assigned a string:
```
char str[80];
str = "my cat is yellow";
```
How would I get yellow?
|
Something like this:
```
char *p = strrchr(str, ' ');
if (p && *(p + 1))
printf("%s\n", p + 1);
```
|
How do I disable echo in a windows console C application?
I don't really want to capture characters with_getch(I still wantCtrl-C) to work. Besides _getch only seems to disable echo forcmdbut not incygwin.
There must be a way to redirect the pipe or modify the console settings.
|
MaybeSetConsoleMode(stolen fromcodeguru) :
```
#include <iostream>
#include <string>
#include <windows.h>
int main()
{
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode = 0;
GetConsoleMode(hStdin, &mode);
SetConsoleMode(hStdin, mode & (~ENABLE_ECHO_INPUT));
std::string s;
std::get... |
How can I copy from beginning up to the last occurrence found?
```
strncpy(name,long_name,strrchr(long_name,'.')+1);
```
|
strrchr()returns a pointer to the last occurance. Subtract the pointer to the start of the string from that and you have the length.
```
strncpy(name,long_name, strrchr(long_name,'.') - long_name);
```
However, this doesnotnull terminatenameautomatically. Make sure you've initialized it to all\0first. Also note tha... |
I wasn't able to find documentation for this. It looks like the R source code usesNewEnvironmentandR_NewHashedEnv, but neither of those are in the public headers, so it looks like they aren't available for me as a user. What function (or what lines of code) should I be using to generate a new ENVSXP?
|
You wantallocSExp:
```
/* C code in foo.c */
#include "Rinternals.h"
SEXP foo() {
SEXP res = allocSExp(ENVSXP);
return res;
}
```
```
> # R code (after running R CMD SHLIB foo.c)
> dyn.load("foo.dll")
> .Call("foo")
<environment: 0x016a4084>
```
|
I am working with a native C client application (not built with Visual Studio) that needs to call a WCF service. I am creating the WCF service, so I have complete control of it.
Most of the information I have found deal with calling WCF from unmanaged C++ clients.
Has anyone tried WWSAPI?
I am hoping to get some d... |
you can usegSOAPis a technology that allows you to create stubs for client and server side code from WSDLs.Hereis step by step tuttorial andthatone for windows
|
I want to know how to check existence and read files (may be with C linux kernel functions) /proc/mtd and /proc/partitions in my program developped in C (for OpenWrt), without using fopen,fread,... functions?
thanks in advance for your help
|
To determine whether a file exists you could try getting the file's stats (creation time, protections, etc.). That would not require you to open or read the file's contents. The error code would tell you whether you simply didn't have permission to perform the action or whether the file didn't exist.
As for reading... |
I am receiving 2 bytes of binary information via Serial in C.
I am receiving them in a char.
So I need to join the 2 chars to make a int but Im unsure how to do that.. first of all the first byte is in binary format and not char format.. So im unsure how I Can convert it into a useable form for my program.
|
JustORthem together ?
```
x = (b1 << 8) | b2;
```
Make sure they're unsigned or cast accordingly (shifting signed stuff is nasty).
|
I am learning NASM as I write bootloaders. So far I have a hello world bootloader. I want to know how to link a c program to it and have the bootloader load it into memory and start executing it's entry point function. I need NASM code as I am a NASM n00b. Thank you very much for you help.
EDIT: Basically I need to k... |
Althoughthis tutorialis for C++, its the exact same procedure (the tutorial lists the parts that are C++ specific, which are just the static ctors & dtors).
when ever your are having problems in this area,osdev.orggenerally has the answer or a tutorial
|
I am writing a program in C with switch statements and I was wondering if the compiler will accept a statement such as
```
case !('a'):
```
I couldn't find any programs online that used the!with a switch statement.
|
Did you actually try it?
Well, I did (gcc on Mac OS X).
! is the logical negation operator, and !(x) returns 1 for an x of 0, and 0 for anything else.'a'has a value which is known at compile-time, so the compiler evaluates!('a')to 0. So
```
case !('a'):
```
is the equivalent of
```
case 0 :
```
It doesn't even g... |
how would you get the last word of a string, starting from the '\0' newline character to the rightmost space? For example, I could have something like this where str could be assigned a string:
```
char str[80];
str = "my cat is yellow";
```
How would I get yellow?
|
Something like this:
```
char *p = strrchr(str, ' ');
if (p && *(p + 1))
printf("%s\n", p + 1);
```
|
How do I disable echo in a windows console C application?
I don't really want to capture characters with_getch(I still wantCtrl-C) to work. Besides _getch only seems to disable echo forcmdbut not incygwin.
There must be a way to redirect the pipe or modify the console settings.
|
MaybeSetConsoleMode(stolen fromcodeguru) :
```
#include <iostream>
#include <string>
#include <windows.h>
int main()
{
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode = 0;
GetConsoleMode(hStdin, &mode);
SetConsoleMode(hStdin, mode & (~ENABLE_ECHO_INPUT));
std::string s;
std::get... |
How can I copy from beginning up to the last occurrence found?
```
strncpy(name,long_name,strrchr(long_name,'.')+1);
```
|
strrchr()returns a pointer to the last occurance. Subtract the pointer to the start of the string from that and you have the length.
```
strncpy(name,long_name, strrchr(long_name,'.') - long_name);
```
However, this doesnotnull terminatenameautomatically. Make sure you've initialized it to all\0first. Also note tha... |
I wasn't able to find documentation for this. It looks like the R source code usesNewEnvironmentandR_NewHashedEnv, but neither of those are in the public headers, so it looks like they aren't available for me as a user. What function (or what lines of code) should I be using to generate a new ENVSXP?
|
You wantallocSExp:
```
/* C code in foo.c */
#include "Rinternals.h"
SEXP foo() {
SEXP res = allocSExp(ENVSXP);
return res;
}
```
```
> # R code (after running R CMD SHLIB foo.c)
> dyn.load("foo.dll")
> .Call("foo")
<environment: 0x016a4084>
```
|
how would you get the last word of a string, starting from the '\0' newline character to the rightmost space? For example, I could have something like this where str could be assigned a string:
```
char str[80];
str = "my cat is yellow";
```
How would I get yellow?
|
Something like this:
```
char *p = strrchr(str, ' ');
if (p && *(p + 1))
printf("%s\n", p + 1);
```
|
How do I disable echo in a windows console C application?
I don't really want to capture characters with_getch(I still wantCtrl-C) to work. Besides _getch only seems to disable echo forcmdbut not incygwin.
There must be a way to redirect the pipe or modify the console settings.
|
MaybeSetConsoleMode(stolen fromcodeguru) :
```
#include <iostream>
#include <string>
#include <windows.h>
int main()
{
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode = 0;
GetConsoleMode(hStdin, &mode);
SetConsoleMode(hStdin, mode & (~ENABLE_ECHO_INPUT));
std::string s;
std::get... |
How can I copy from beginning up to the last occurrence found?
```
strncpy(name,long_name,strrchr(long_name,'.')+1);
```
|
strrchr()returns a pointer to the last occurance. Subtract the pointer to the start of the string from that and you have the length.
```
strncpy(name,long_name, strrchr(long_name,'.') - long_name);
```
However, this doesnotnull terminatenameautomatically. Make sure you've initialized it to all\0first. Also note tha... |
I wasn't able to find documentation for this. It looks like the R source code usesNewEnvironmentandR_NewHashedEnv, but neither of those are in the public headers, so it looks like they aren't available for me as a user. What function (or what lines of code) should I be using to generate a new ENVSXP?
|
You wantallocSExp:
```
/* C code in foo.c */
#include "Rinternals.h"
SEXP foo() {
SEXP res = allocSExp(ENVSXP);
return res;
}
```
```
> # R code (after running R CMD SHLIB foo.c)
> dyn.load("foo.dll")
> .Call("foo")
<environment: 0x016a4084>
```
|
I am working with a native C client application (not built with Visual Studio) that needs to call a WCF service. I am creating the WCF service, so I have complete control of it.
Most of the information I have found deal with calling WCF from unmanaged C++ clients.
Has anyone tried WWSAPI?
I am hoping to get some d... |
you can usegSOAPis a technology that allows you to create stubs for client and server side code from WSDLs.Hereis step by step tuttorial andthatone for windows
|
if in the beginning of my file i do
```
#define dbg_kprintf \
if (x_var) kprintf
```
I late on do statements using
```
dbg_kprintf ("blablabla");
```
My question is that will dbg_kprintf be only defined if xvar is defined somewhere else? If it is not then will dbg_kprintf statements not be used at compile time?... |
No, that will either compile into a run-time check of the variable, or nothing (if the variable is in fact compile-time constant with a false value and the optimizer feels like eliminating the dead code) or a call always (if it's a compile-time constant with a true value). So, now you know.
The typical way to ensure ... |
I have programmed a self-made concat function:
```
char * concat (char * str1, char * str2) {
for (int i=0; i<BUFSIZ; i++) {
if (str1[i]=='\0') {
for (int j=i; j<BUFSIZ; j++) {
if (str2[j-i]=='\0') return str1;
else str1[j]=str2[j-i];
}
}
... |
In C++ use string instead ofchar*and functions:std::string result = std::string(buf) + temp1 + temp2;
|
Can someone explain me how to choose the precision of a float with a C function?
Examples:
theFatFunction(0.666666666, 3)returns 0.667
theFatFunction(0.111111111, 3)returns 0.111
|
You can't do that, since precision is determined by the data type (i.e.floatordoubleorlong double). If you want to round it for printing purposes, you can use the proper format specifiers inprintf(), i.e.printf("%0.3f\n", 0.666666666).
|
I have a dll with a c interface, the functions of which will return error codes, I will also provide an additional function that returns the last error. Does this sound sensible? can anyone point me at any examples that i can use as a template please?
|
"The last error" is not a very useful or reliable concept in the context of a DLL. What if the DLL is being used by several processes or threads?
|
I know the virtual memory separates 2G(for kernel)/2G(for user) in Windows.
But why the address of variable isn't stack continually?
Likes 0x22ff74,0x22ff78,0x22ff82,0x22ff86 ? Does it mean that Windows use sandbox mechanism in user process?
|
That's exactly what virtual memory is. The operating system provides each program with its own private address space. In reality the operating system is in charge of mapping those virtual addresses back to the physical address space without the application being aware.
As you noticed this means that two applications ... |
fromthis page
i found
```
cd ${YOUR_PATH}/L27.12.1-P2/kernel/android-2.6.35
git fetch http://review.omapzoom.org/p/kernel/omap refs/changes/22/13722/2 && git cherry-pick FETCH_HEAD
```
when i run this it makes paches and shows me how manny files are changed.
But what if i want to know by running this which files a... |
You should be able to run'git show', which will show all the changes from the currentHEADto theprevious commiton a line level.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:how to extract plain text from ms word document file in pure c++?
I am developing a c\c++ program to convert .doc file to formatted plain text under Linux.Is there any open source library to accomplish this?
Thanks!
|
Fromhere.
You could have a look at the open source C library used by Abiword,wv.
You can also call out to a batch convert tool
Open source batch converter, based on OpenOffice:http://dag.wieers.com/home-made/unoconv/The open source for unix:http://www.wagner.pp.ru/~vitus/software/catdoc/Proprietary for
windows:http... |
I am working on project where I need to print a receipt through a Hengstler C51 Thermal Printer. The device is working fine and it's printing images too.
I need to write a C program which can open my printer and print my preformatted receipt which is going to contain a simple logo.
I can not figure out how to procee... |
might just be easier to make program that creates your image file instead of programming the printer. I can't find anything on this thing. Your best bet is to trial and error on that API and Docs they provide, if you don't like my idea.
|
Using C, I am trying to create an Access 2007 database file using ODBC by way of theSQLConfigDataSourcefunction.
```
char szDriverName[] = "Microsoft Access Driver (*.mdb, *.accdb)";
char szAttr[] = "CREATE_DB=c:\access2007.accdb";
SQLConfigDataSource(NULL, ODBC_ADD_DSN, szDriverName, szAttr);
```
I want the file ex... |
Use CREATE_DBV12:
```
char szDriverName[] = "Microsoft Access Driver (*.mdb, *.accdb)";
char szAttr[] = "CREATE_DBV12=c:\access2007.accdb";
SQLConfigDataSource(NULL, ODBC_ADD_DSN, szDriverName, szAttr);
```
|
I'm trying to compare a character string with the argv argument.
I have this in my main:
```
int main(int argc, char *argv[])
```
Now if I write
```
if (argv[2] == 'squared')
```
the IDE tells me that I have a multiple character constant or that the char* is too long for its type or something similiar.
Is there ... |
Use strcmp and a real string, not a multi character constant.
```
strcmp(argv[2], "squared") == 0
```
|
I am developing a protocol over UDP to be used in a local network, there will be only a switch (cisco, 3com, etc) between source and destination, both Linux systems, same MTU.
How often should I expect udp packets to be duplicated (obviously not by me but by the switch or maybe the server) at the destination in this c... |
Switches will send packets to all interfaces when using broadcasts or under extreme conditions (full MAC Address Table). This can lead to duplication if there is a loop between two or more switches and if the Spanning Tree Protocol is not used. So the answer is rarely.
|
The application in question allows users to define their own messages (mainly for customization and/or localization purposes) in plain-text configuration file, which are passed to printf-style functions at runtime. If the user-defined formatting string is faulty, a whole lot of bad things can happen.
What is the best... |
Define your own formatting language, which your code translates into a valid format string, thereby restricting what trouble the user can get into (for example, not allowing % at all, and defining your own symbol/marker to use to indicate a % should appear in the output).
|
Writing a program to retrieve data from an sqlite database keeps returning no results despite the exact same query in the sqlite cli returning the expected results.
```
#include <stdio.h>
#include <sqlite3.h>
sqlite3 * db;
sqlite3_stmt * locationgetint;
int locationInt(char * string){
sqlite3_bind_text(location... |
As Sjoerd said, removing the quotes worked.
|
One can get information about a process according to its PID reading files in /proc/PID directory. Is there any library providing such information directly?
|
You may uselibproc-dev
Andhereis a little example
|
Suppose I have anifstatement with areturn. From the efficiency perspective, should I use
```
if(A > B):
return A+1
return A-1
```
or
```
if(A > B):
return A+1
else:
return A-1
```
Should I prefer one or another when using a compiled language (C) or a scripted one (Python)?
|
Since thereturnstatement terminates the execution of the current function, the two forms are equivalent (although the second one is arguably more readable than the first).
The efficiency of both forms is comparable, the underlying machine code has to perform a jump if theifcondition is false anyway.
Note that Python... |
I have a file named common.h where all the variables and functions have been defined. Is there an easy way by which I could generate and copy the names of all the variables and functions defined ? I have more than 2,000 functions and variables defined all together and its futile to copy them one by one.
I am currentl... |
You could usectags. Just issue
```
ctags -x common.h
```
from a terminal. A version of ctags for Windows also exists.
|
I'm usingthis type of splinein my code and I'm wondering if the algorithm can benefit from the use of SIMD instructions. (NEON on ARM) The code used is a C translation of the following sources (in Fortran):
http://pages.cs.wisc.edu/~deboor/pgs/chol1d.f(the most CPU consuming procedure)http://pages.cs.wisc.edu/~deboor... |
It looks like there are serial dependencies in the loops, so probably the only way that this will lend itself easily to vectorization with SIMD is if you have multiple data sets (e.g. 4) which you can operate on in parallel. These data sets would need to be the same size.
|
Is there a way to obtain a list of functions that were NOT inlined anywhere? Either by passing an option to gcc or by inspecting the binary?
EDIT: I know how to explicitly ask for a function not to be inlined by using gcc's builtin attribute noinline.
|
Add-fdump-ipa-inlineto your compiler options.
Grep the fileyoursourcefile.inlinewhich is created next to the object file for "Considering inline candidate" to find out all functions that the compilerconsideredinlining.
Grep the file for "Inlined into" to find out all functions that the compiler finallydid inline.Gre... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:Marshaling c structures in c#
Actual C structures:
```
typedef struct procedure
{
char code[8];
}procedure;
typedef struct p45_cldxed24
{
procedure p45_cldxed[8];
}p45_cldxed24;
```
What would be the equivalent C# structure for p45_... |
I believe the code would be as follows:
```
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
struct p45_cldxed24
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
procedure[] p45_cldxed;
}
```
The key here is thatMarshalAsattribute.
|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question
How to fetch first two bytes from the string "DDMMYYHHMMSS" and fill the below structure.
```
mytime.tm_se... |
May be I don;t understand the question, but why can't you do the following:
```
assert(strlen(timestring) == 12);
char ss[3];
strncpy(ss, ×tring[10], 2);
mytime.tm_sec = atoi(ss);
// same for others
```
UPD: No, stop right now. I forget aboutstrptime(check man pages). It should help you
|
How do I concatenate (or even assign) two strings (TCHARarrays, I guess) in MinGW with GCC?
StrCatBuff?#include <shlwapi.h>and-lshlwapido work, but you'renot supposed to use it_tcscat?Seems not to existStringCchCatSeems not to exist.strsafe.hdoesn't exist.
The same holds true for their respective assignment function... |
_tcscat(or the "secure" version,_tcscat_s) works just fine for concatenating arrays ofTCHARs. You have to includetchar.hin order to use either of these functions.
The same should be true forStringCchCat, which as you mention is defined instrsafe.h.
If you're missing these header files, make sure that you've installe... |
I'm looking to convert this line of C code to C#:
```
const u64 a = 1, b = -a;
```
So my understanding is that both constants are unsigned 64-bit integers. If so, what is the result going to look like?
Or is the second constant actually promoted and therefore defined as a signed integer?
|
This would be the equivalent C#:
```
const ulong a = 1, b = unchecked((ulong)-1);
```
Or more simply:
```
const ulong a = 1, b = 18446744073709551615;
```
|
As many books mentioned, the difference with C++ struct and class is the access control descriptor. Thus I am wondering if the following statement is right:
struct in C is unboxed: members in the struct are plainly located next to where the struct is allocated.
But struct in C++ is a boxed type like class: members... |
Looks like complete nonsense to me.
Members are not magically "located somewhere else", no pointers are involved, and headers havenothing to do with it whatsoever. The C++ compiler doesn't even know that headers exist!
|
Is it possible to set values for default parameters in C? For example:
```
void display(int a, int b=10){
//do something
}
main(){
display(1);
display(1,2); // override default value
}
```
Visual Studio 2008, complaints that there is a syntax error in -void display(int a, int b=10). If this is not legal in C, w... |
Default parameters is a C++ feature.
C has no default parameters.
|
I have to iterate through all alphanumeric characters, including lower case and upper case and numbers and for each one, I have to call the crypt command.
So, I have to check for Aa, aA, 1a, a1, 1A, A1 etc till all possible combinations and call crypt KEY crypt_file.
Is there an efficient way to do this?
Thanks
|
You can put the characters into an array. Something like:
```
const char vals[] = { '0', '1', '2', ..., 'a', 'b', ... 'Z' }; // Probably better to generate it programatically
```
A double "for" loop should do it:
```
int i;
for (i = 0; i < kNumVals; i++) // kNumVals is the number of characters in your array
{
i... |
There i something i dont get, if have the following:
```
double average (double scores[]){
double sum = 0;
int n;
int nscores = sizeof(scores)/sizeof(double);
for (n=0 ;n<nscores ;++n){
sum+=scores [n];
return sum/nscores;
}
```
and i send this function an array like this:
```
double scores[3]={1,2,3};
```
... |
sizeof(scores), inside the function, is equivalent tosizeof(double *): the compiler has no way to tell, at that point, how big the array was.
Itwon'tbe zero, but becausesizeof(scores)andsizeof(double)are both integer-type expressions,sizeof(scores)/sizeof(double)is integer division, so ifsizeof(scores) < sizeof(doubl... |
Say I have a program that creates a database file, and imports data to it from a.sqlfile.
If I don't want a random.sqlfile floating around my directory, is there a way to compile this static file into the executable for use without having to copy it's contents into a string in a C file? A define statement perhaps?
|
Usexxd
```
$ xxd -i data.sql > data.sql.c
```
then include (or copy/paste) the resulting c file (not a header)
You can include for global ...
```
#include <stdlib.h>
#include "data.sql.c" /* global scope */
```
... or function scope
```
int foo(void) {
# include "data.sql.c" /* function scope */
}
```
|
I have an assignment I'm working on that required me to render an image only using hidden lines. I'm finding stuff online on how to remove hidden lines but Ive been unsuccessful at figuring out how to reverse the code to make it so that it only draws the hidden lines.
Usually when i come to Stack Overflow I like to p... |
If I understand you correctly, you can use an approach similar to Depth Peeling using multiple render passes: Draw the scene once, keep the resulting depth buffer. Draw the scene again, now discard all fragments whose z value is less or equal to the value in the stored z-buffer and draw all others.
|
Anyone know of a possible reason why fprintf maynot work for me when using the android NDK?
```
FILE * f = fopen("/sdcard/newfile.txt", "w+");
fprintf(f, "testing\n");
```
I do have the write external storage permission in the android manifest. And this code creates a file newfile.txt but it's empty.
Is there any... |
I think you have to close the stream with something like "fclose":
```
FILE * f = fopen("/sdcard/newfile.txt", "w+");
fprintf(f, "testing\n");
fclose(f);
```
|
What is the exact difference between thegetchandgetcharfunctions?
|
getchar()is a standard function that gets a character from the stdin.
getch()is non-standard. It gets a character from the keyboard (which may be different from stdin) and does not echo it.
|
I am trying to compile theHelloexample in directorylib/Transforms/Hello, which is basically a Hello World of LLVM pass, but I get the following error when I try to compile it usingmake.
```
../../../Makefile.common:61: ../../../Makefile.config: No such file or directory
../../../Makefile.common:69: /Makefile.rules: N... |
If you built LLVM + Clang according to instructions, theHellosample should have already been built. Go tolib/Transforms/Helloin the build directory(where you ranconfigureand thenmake). There should be aDebug+Asserts(or whatever configuration you compiled) there. And you can also runmakefrom there again.
In general, y... |
i convert image to HSV after it i make the threshold the yellow color so the code is
cvInRangeS(imgHSV, cvScalar(112, 100, 100), cvScalar(124, 255, 255), imgThreshed);
but it doesn't work always give me black image .
|
You should try this tutorial for"tracking yellow objects".
It gives a HSV range ofcvInRangeS(imgHSV, cvScalar(20, 100, 100), cvScalar(30, 255, 255), imgThreshed)for yellow object.
If you have any doubt on selecting color, try this :http://www.yafla.com/yaflaColor/ColorRGBHSL.aspx
|
The current size of long int in my system is 4 bytes. Is it possible to increase its size? In case it is not possible how to deal with situations where we need integral data type with specified byte size. The applications include factorial, permutations, combinations etc.
|
how to deal with situations where we need integral data type with
specified byte size
Usestdint.htypes likeuint24_t,uint32_t,uint64_t, etc.
|
What happens in C if we do something like this in Java:
```
temp.next = temp.next.next;
```
What will happen to temp.next node? In Java there is a dump/ garbage collector; is there something similar in C?
|
Nothing will happen to it. It will continue to use memory and you will have lost any means to use it or free it.
In C you have to explicitlyfreestuff you obtained viamallocwhen you're done with it, there's no such thing as reference counting or garbage collection.
|
I've got a very big program which compiles with gcc without warnings.
If I turn on c99 mode --std=c99 on the command line, it gives a huge number of warnings and errors.
But I love the idiomfor(int i=0; i<20; i++){ code }
in place of{int i; for (i=0; i<20; i++){ code }}
Is there any way to tell gcc to allow this a... |
It is likely that the warnings and errors are because-std=c99requests standard-conforming C99, which means that many platform-specific functions that pollute the C99 namespace are not defined.
Instead, you should try--std=gnu99, which is the C99-equivalent to the default mode ofgnu89.
|
I'm using a 3rd party API C sources where special documentation blocks are as following
```
/****************************************************************************************
* @fn fn
*
* @brief brief
*
* @param param
*
* @return return
****************************************... |
I suggest to create an input filter that replaces/******by/**and add that to theINPUT_FILTERoption in the configuration file. If you have the Unix commandsedon your system, the following would do the trick:
```
INPUT_FILTER = "sed -e 's|/\*\*\**|/**|g'"
```
|
Suppose I ve
```
int *a,*b;
a= malloc(5*sizeof(int));
b= malloc(5*sizeof(int));
```
and subsequently assign values.
Let a - 1, 2, 3, 4, 5b - 6, 7, 8, 9, 10
Is there a method to concatenate both these malloced arrayswithout using furthermalloc,reallocormemcpy? There shud not be a malloc of 10 locations!
I must... |
a= malloc(5*sizeof(int));
You only allocated 5 ints to a, so no, you can't do it without some form or memory allocation (malloc/realloc), sincea[8]would be illegalto begin with.
I must be able to get a[8]=9 after executing, without the overhead of
moving the arrays
Since since you are working with contiguous memo... |
I have an Array as (filled with zeros and ones) -> ArrayWithContent[5] = {1,0,0,1,1};
Now I want this to be converted into an variable so I can read out the total value of this.
0001 0011 = 19
```
for(i=0; i<5; i++)
{
OneValue = ArrayWithContent[i];
Variable = OneValue;
Variable >>= 1; // Se... |
```
Variable = 0;
for (i = 0; i < 5; i++)
{
Variable = (Variable << 1) | ArrayWithContent[i];
}
```
Here:
(Variable << 1)shifts the current value ofVariableone bit to the left.... | ArrayWithContent[i]replaces the least-significant bit of the shifted value withArrayWithContent[i].Finally,Variable = ...assigns th... |
im trying to make my own kernel....
my kernel is loaded through grub...which i suppose creates the gdt required for me...so i did not create the gdt myself and continued creating the idt ...
now when i try a divide by zero exception my fault handling method is not called....
i have lidt in my asm file , set the entr... |
There's no division by 0 in the code.
|
I am searching for way to create a somewhat random string of 64k size.But I want this to be fast as well. I have tried the following ways:
a) read from /dev/random -- This is too slowb) call rand() or a similar function of my own -- a soln with few(<10) calls should be ok.c) malloc() -- On my Linux, the memory region... |
/dev/randomblocks after its pool of random data has been emptied until it gathered new random data. You should try/dev/urandominstead.
|
Hey I need a little help with unsigned char bit access. I need to test to ensure that "channel" which is an unsigned char (UCHAR) is 6 digits long (i have that) and that the the number enter is infact a binary number (aka 1s or 0s). I at a loss for how to access it. Any help would be great!
```
void binEnter(void *ch... |
Make a loop to check each digit.
```
char *string = channel;
for (j = 0; j < 6; j++)
{
if ((string[j] != '0') && (string[j] != '1'))
{
// error
}
}
```
You could also just usestrtol(3)and check the result inendptrto see if you got a 6-digit number.
|
What happens in C if we do something like this in Java:
```
temp.next = temp.next.next;
```
What will happen to temp.next node? In Java there is a dump/ garbage collector; is there something similar in C?
|
Nothing will happen to it. It will continue to use memory and you will have lost any means to use it or free it.
In C you have to explicitlyfreestuff you obtained viamallocwhen you're done with it, there's no such thing as reference counting or garbage collection.
|
I've got a very big program which compiles with gcc without warnings.
If I turn on c99 mode --std=c99 on the command line, it gives a huge number of warnings and errors.
But I love the idiomfor(int i=0; i<20; i++){ code }
in place of{int i; for (i=0; i<20; i++){ code }}
Is there any way to tell gcc to allow this a... |
It is likely that the warnings and errors are because-std=c99requests standard-conforming C99, which means that many platform-specific functions that pollute the C99 namespace are not defined.
Instead, you should try--std=gnu99, which is the C99-equivalent to the default mode ofgnu89.
|
I'm using a 3rd party API C sources where special documentation blocks are as following
```
/****************************************************************************************
* @fn fn
*
* @brief brief
*
* @param param
*
* @return return
****************************************... |
I suggest to create an input filter that replaces/******by/**and add that to theINPUT_FILTERoption in the configuration file. If you have the Unix commandsedon your system, the following would do the trick:
```
INPUT_FILTER = "sed -e 's|/\*\*\**|/**|g'"
```
|
Suppose I ve
```
int *a,*b;
a= malloc(5*sizeof(int));
b= malloc(5*sizeof(int));
```
and subsequently assign values.
Let a - 1, 2, 3, 4, 5b - 6, 7, 8, 9, 10
Is there a method to concatenate both these malloced arrayswithout using furthermalloc,reallocormemcpy? There shud not be a malloc of 10 locations!
I must... |
a= malloc(5*sizeof(int));
You only allocated 5 ints to a, so no, you can't do it without some form or memory allocation (malloc/realloc), sincea[8]would be illegalto begin with.
I must be able to get a[8]=9 after executing, without the overhead of
moving the arrays
Since since you are working with contiguous memo... |
I have an Array as (filled with zeros and ones) -> ArrayWithContent[5] = {1,0,0,1,1};
Now I want this to be converted into an variable so I can read out the total value of this.
0001 0011 = 19
```
for(i=0; i<5; i++)
{
OneValue = ArrayWithContent[i];
Variable = OneValue;
Variable >>= 1; // Se... |
```
Variable = 0;
for (i = 0; i < 5; i++)
{
Variable = (Variable << 1) | ArrayWithContent[i];
}
```
Here:
(Variable << 1)shifts the current value ofVariableone bit to the left.... | ArrayWithContent[i]replaces the least-significant bit of the shifted value withArrayWithContent[i].Finally,Variable = ...assigns th... |
im trying to make my own kernel....
my kernel is loaded through grub...which i suppose creates the gdt required for me...so i did not create the gdt myself and continued creating the idt ...
now when i try a divide by zero exception my fault handling method is not called....
i have lidt in my asm file , set the entr... |
There's no division by 0 in the code.
|
I am searching for way to create a somewhat random string of 64k size.But I want this to be fast as well. I have tried the following ways:
a) read from /dev/random -- This is too slowb) call rand() or a similar function of my own -- a soln with few(<10) calls should be ok.c) malloc() -- On my Linux, the memory region... |
/dev/randomblocks after its pool of random data has been emptied until it gathered new random data. You should try/dev/urandominstead.
|
Hey I need a little help with unsigned char bit access. I need to test to ensure that "channel" which is an unsigned char (UCHAR) is 6 digits long (i have that) and that the the number enter is infact a binary number (aka 1s or 0s). I at a loss for how to access it. Any help would be great!
```
void binEnter(void *ch... |
Make a loop to check each digit.
```
char *string = channel;
for (j = 0; j < 6; j++)
{
if ((string[j] != '0') && (string[j] != '1'))
{
// error
}
}
```
You could also just usestrtol(3)and check the result inendptrto see if you got a 6-digit number.
|
I have a png file that is to be stored in a database, however, even when passing a length tosqlite3_bind_blob()it stops filling in the value at the first nul character.
Here's the code in question:
```
fseek(file,0xC,SEEK_CUR); // Skip to 12 (0xC) and read everything (It's a raw png file)
char content[size-0xC];
fre... |
The sqlite cli interface has a bug where it parses blobs as strings and stops printing them early, including if it's told to send output to a file.
|
I am trying to build my understanding of OpenGL and see how the 'pros' do things. I am looking for examples of these objects (preferably inC) - I've learned through examples so I think it would help others to see it as well :)
I'm very much a nubie at openGL so this may be a stupid question - I'm just looking for obj... |
You might be interested in thislist of OpenGL based games and applications, particularly the Open Source games.
Also,Ogre 3Dis a well-known Open Source graphics engine with an OpenGL renderer.
|
I saw some code that was something like this
```
int *func2(int *var) {
//Do some actual work
return var;
}
int *func1(int *var) {
return func2(var);
}
int main() {
int var;
var = func1(&var);
return 0;
}
```
This seems like an incredible waste to me but I figured the intermediate function ... |
Don't do premature optimization. Focus on writing readable code. Even without optimization, the extra function call probably has a minimal effect on performance. The compiler may choose to inline it.
If you have performance issues later, you can test and profile to find the bottlenecks.
|
I'm getting this warning: (-std=c99 -pedantic)
```
warning: implicit declaration of function ‘strndup’ [-Wimplicit-function-declaration]
```
but I'm importing these libs:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
```
So what?! :(
```
// file.c:
#include "file.h"
strndup(...)
// file... |
The issue is your usage of the-std=c99option. Sincestrndup()isn'tpart of C99, and you're asking the compiler to go into standards compliant mode, it won't provide the prototype for it. It still links of course, because your C library has it.
While you may be able to coaxgccinto providing it by specifying feature macr... |
I am writing a program that creates an image file. I want the "original" image to be hard-coded in the program's binary.
I was thinking...
```
char image[] = {
#include"image.jpg"
}
```
But I need to somehow convert the image into a format that can be #included into a c file as a char array?
|
Ok, use the unix toolxxdto create a c char array import of a given binary file, Like so:
```
$ xxd -i imgfile.dat > imgfile.h
```
This should produce output like:
```
unsigned char imgfile[] = {
0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x0a
};
unsigned int imgfile_len = 12;
```
See also:... |
I am trying to 'prettify' some code that makes a log file and in the log file I want to print the name of the input files and what settings were used in a nicely formatted #-box. I need to be able to get the length of an entered argument which has to be stored by the GNU getopt somewhere for it's internal malloc, at l... |
Where your code stores the value, it is available in the
```
extern const char *optarg;
```
variable, and you can simply usestrlen()to compute the length of the string.
|
I found a type of variable that has a value of INTEGER (0...224- 1). a guy who made the code decide to put a variable with type of uint32_t var; and put the result of this with 0xFFFFFF
how does this uint32_t & OxFFFFFF is able to handle the value of INTEGER (0...224- 1) ?
As I understand, with masking 0xFFFFFF you ... |
Masking with0xffffffonly makes sure that the value that is stored never is outside the 0..2^24-1 range. Anything but the lower 24 bits are discarded.
If you for example have the value-1and mask it, it will end up as the value0xffffff. The value has changed, but now it's inside the valid range.
|
was wondering what would be the best data structure to store a telephone directory when it has to be accessed via both name and number?
|
There is a bimap:http://commons.apache.org/collections/apidocs/org/apache/commons/collections/BidiMap.html
|
What are the sources or clock of Linux time functions ?
Are all (time , gettimeofday ...) getting updated clock values from reading same hardware component? Or are they all just retrieving some current time value maintained by Kernel?
Any of these function will read directly from BIOS ?
|
It varies depending on a large number of factors including what hardware is available, whether time synchronization is in use, and a number of other factors. On typical modern hardware, the TSC or HPET is read and scaled according to factors maintained by the kernel's timekeeping system.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.