question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
Any given point of time, how can i get the memory size utilized by each thread?
|
If all you want is aheap profilerconsider Google performance tools with their own allocator TCMalloc.
http://code.google.com/p/google-perftools/
An alternative high performance allocator is jemalloc which provides statistics reporting including per-thread cache bin details withmalloc_stats_print()
http://www.canonw... |
I'm using those imports
```
#include <stdio.h>
#include <math.h>
```
and I'm gettingundefined reference to `round'at this line:
```
double res = round(atof(nextVal));
```
nextValis a double value read from a file.
I'm using Eclipse INDIGO.
|
In command line, you must specify-lmoption to gcc to link the math lib. You have to find how to do so in eclipse.
|
I'm wondering if it is safe to callpthread_cancel()on a terminated thread. I couldn't find any hints in the manual page. Thanks in advance for any hints.
Edit: Maybe I wasn't accurate enough. I'mnottalking about threads terminated by an earlier pthread_cancel() but about threads that simply returned from their thread... |
I think itneedsto be safe, orpthread_cancelwould be problematic (next to unusable).
Indeed, if it wouldn't be safe, every call topthread_cancelwould have to be enormously complicated by checking the thread is alive (and ensuring it stays alive until you get to cancel it). A simple "are you still there" wouldn't do.
... |
```
struct s
{
int a;
float b;
int c;
}
```
How is this structure members stored in memory location?
My understanding is that when a structure variable is allocated then memory for the
structure members will also be allocated. If 1000 is the starting address then a will be at
1000, b will be 1004, and c will ... |
Assumingsizeof(int) == sizeof(float) == 4and that the compiler doesn't decide to put some padding in, your answer is correct. I don't know what "Integers and float will have different address spaces in the memory" means, so I'm not sure I can answer your final question.
|
This question already has answers here:What does the operation c=a+++b mean?(9 answers)Closed9 years ago.
```
#include <stdio.h>
int main()
{
int a=8,b=9,c;
c=a+++b;
printf("%d%d%d\n",a,b,c);
return 0;
}
```
The program above outputsa=9 b=9andc=17. Ina+++bwhy is the compiler takesa++and then adds w... |
I like the explanation fromExpert C Programming:
The ANSI standard specifies a convention that has come to be known as
themaximal munch strategy. Maximal munch says that if there's more
than one possibility for the next token, the compiler will prefer to
bite off the one involving the longest sequence of characters... |
i wrote the following program
```
#include <stdio.h>
main()
{
int i = 2;
float c = 4.5;
printf("%d\n",c);
printf("%f\n",i);
return 0;
}
```
though i know this is the wrong practice,when i run the program i got the answer as
```
0
4.500000
```
but when i exchanged the printf statements a little bit this w... |
printf doesn't convert it's arguments. It's looking at the memory containing a float and printing it as if it were an integer - it's like taking an MP3 file and asking word to open it as if it were a doc.
A floating point number is stored in a completely different way in memory to an integer - it's not just an intege... |
```
// gcc -o 0 $(pkg-config --cflags --libs gtk+-2.0) 1.c
#include <gtk/gtk.h>
int main (int argc, char *argv[]) {
GFile *f1 = NULL;
f1 = g_file_new_for_path ("/home/user/1.txt");
g_printf ("File loaded successfully.\n");
return 0;
}
```
When I run this program it causes segmentation fault at g_file_... |
You need to callg_type_init()before usingg_file_new_for_path-- as perthis thread. After that, the program works.
|
```
& # disown the functions
```
As we all know&put a task into background, and most importantly disowns the task.
But how is it achieved?
|
Without a&, the shell forks itself, callsexecvein the child process to start the task, and waits viawaitorwaitpidfor the child to terminate (which suspends the shell), not doing anything else than that.
When starting a background task, the shell forks itself again, callsexecveto start the task in the child process, b... |
Is this C code:
```
/* LERP(a,b,c) = linear interpolation macro, is 'a' when c == 0.0 and 'b' when c == 1.0 */
#define LERP(a,b,c) (((b) - (a)) * (c) + (a))
```
http://www.brucelindbloom.com/index.html?Eqn_XYZ_to_T.html
Equals this C# code?
```
private static double LERP(double a, double b, double c) { return ... |
no.
consider the following:
LERP(x++,1,2);
The c code might also have a side effect of increasing x twice [it is undefined as mentioned by @phresnel], while the c# code is perfectly defined, and will increase x only once.
the result also might be different, since the firstaand the second one [in the macro] might ha... |
Is it possible to create an array of arrays in c
Thank you.
|
It's the same as for example in PHP:
```
int arrayInArray[10][50];
```
You read data out of it with:
```
printf("%d", arrayInArray[3][37]);
```
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago.
I have purchasedThe C Programming L... |
You should use an IDE (Integrated Development Environment). I've chosenCode:Blocksa long time ago and I am still happy with it. Alternatively you can use NetBeans, Eclipse, DevCpp, ... There are a lot of IDEs for C or C++ available.
|
I'm a newbie to GTK+, I want to use GtkPlug/GtkSocket to embed another application with my application. I referred to Devhelp, but only a few introduction about these two class. I also searched many days, but I failed to find a demo.
Can somebody show me how to use GtkPlug/GtkSocket? complete source code and explanat... |
There used to be a section in the GTKmm tutorial, here is the content that is no longer present:https://gitlab.gnome.org/GNOME/gtkmm-documentation/-/commit/2c11fad94458d4e72998e13aa1de8d7f742ce74b
Even though it is in C++, it gives a good example of how to write a simple plug-socket system. However, since I originall... |
What's the "correct" way to write a decreasing loop with a size_t value and a boundary condition. Example incorrect implementation:
```
for (size_t elemNum = listSize-1; elemNum >= 0; --elemNum) { /* ... */ }
```
When it reaches zero it will wrap around to the max value rather than acting as a boundary condition. It... |
The most succinct approach is to use post-increment:
```
for (size_t i = listSize; i--;) ...
```
|
I have a struct that I use in header file1. I now also need that struct in header file2 because it is used in function prototypes. I have included header file1 in header file2, but this give a lot of complaints of redefition of types after compiling? Is there a straightforward way to do it? I have googled about nested... |
Sure there is. Useinclude guards.
```
file1.h
#ifndef FILE1_H
#define FILE1_H
/* Define everything here. */
#endif
```
This way you can include file1.h over and over. In particular, you should always use include guards if a headerdefinesthings.
As a side note, if you don't need the details of the struct (that is... |
```
#include<stdio.h>
int main()
{
unsigned int a=6;
int b=-20;
(a+b>6)?puts(">6"):puts("<=6");
return 0;
}
```
The above code outputs>6. But I got a doubt.b=-20will hold a negative value (-18)
after doing the 2's complement as it's a signed integer. So it should output<=6but its
giving an output a... |
From the C99 standard, section 6.3.1.8 ("Usual arithmetic conversions"):
if the operand that has unsigned integer type has rank greater or
equal to the rank of the type of the other operand, then the operand
with signed integer type is converted to the type of the operand with
unsigned integer type.
Basically,... |
I am interested in writing an "introduction" on the index.html page, rather than have blank space. Is this a feature supported by the Doxygen tool, or must I put together a hack?
|
This is answered by the first question in theDoxygen FAQ:
1. How to get information on the index page in HTML?You should use the \mainpage command inside a comment block like this:/*! \mainpage My Personal Index Page
*
* \section intro_sec Introduction
*
* This is the introduction.
*
* \section install_sec Inst... |
Is it a good practice to lock a mutex from the main thread, and release from another thread?
Or should I make sure a thread will do it all in one? ie: lock, and unlock
|
http://www.manpagez.com/man/3/pthread_mutex_unlock/
(also from the POSIX spec site:http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_lock.html)
If the current thread holds the lock on mutex, then thepthread_mutex_unlock()function unlocks mutex.Callingpthread_mutex_unlock()with a mutex that the ... |
I have a c array:
```
CGPoint hillKeyPoints[kMaxHillKeyPoints];
```
How do I access this from another class?
If I had anNSArrayI would use a pointer to access the array, ie:
```
hillClass.[hillKeypoints objectAtIndex:0];
```
How does this work in c?
Thanks
|
C doesn't have classes. C just has structures and ordinary functions. Access is straightforward using one of the structure member access operators.or->(depending on whether or not you have a pointer) and the array subscripting operator[]:
```
typedef struct HillStruct
{
CGPoint hillKeyPoints[kMaxHillKeyPoints];... |
instead of checking every input pointer argument withifconditionif( in != NULL ), is there better way to do this. One method is to create some macros, like
```
#define CHECK_ARG(x) if(!(x)) { return 0; }
```
In code it's look like this
```
int some_func( int * first_arg, int * second_arg )
{
CHECK_ARG( first_ar... |
I would use someASSERTin there instead - at least in your debug version.
Also, what George said - its not readable and clear that it returns0.
|
I am trying to find the minimun number in an array using recursive function.but my code gives segemtation fault .
```
main()
{
int a[5]={2,1,4,5,3};
int n=1;
fumi(a,n,a[0],5);
}
fumi(int a[],int n,int min,int t)
{
if(n==t)
{
printf("%d",min);
}
if(a[n]<min)
{
min=a[n];... |
you should alsoreturnafterprintf("%d",min);otherwise, you checkif (a[t] < min), anda[t]was not allocated.
```
fumi(int a[],int n,int min,int t)
{
if(n==t)
{
printf("%d",min);
return; //This line was added
}
if(a[n]<min)
{
min=a[n];
}
return(fumi(a,n+1,min,t));
}
```... |
I want to useU32type but I can't find the header where it is defined. Does anyone know?
|
There is no standard type calledU32, but if you#include <cstdint>(stdint.hfor C) you can usestd::uint32_t1, a 32 bit unsigned integer, which is (I assume) what you want.
Here isa list of types in thecstdintheader:
```
namespace std {
int8_t
int16_t
int32_t
int64_t
int_fast8_t
int_fast16_t
... |
I have a question, does anyone know why the variables have to be definedinitializedat the beginning of a function? Why can't you initialize or define variables in the middle of a function in C as in C++?
|
This is a tradition which comes from early C compilers, when compiler needs all local variable definitions before the actual code of function starts (to generate right stack pointer calculation). This was the only way of declaring local variables in early C language, both pre-standard (K&R) and first C standard, C90, ... |
I have just began a new C project, using gcc (currently 4.5.2). Now, before it grows too big, I want to start unit testing it. After some googling I've realized that there are numerous of frameworks to choose from. I cannot afford testing them all.
Note that I don't mind using g++ for the unit tests, as long as I can... |
I've played with libcheck, which is pretty good. It's been a while since I last used it, but it does the job, and is just straight C.
|
I've seen the tilde operator used in the ELF hashing algorithm, and I'm curious what it does. (The code isfrom Eternally Confused.)
```
unsigned elf_hash ( void *key, int len )
{
unsigned char *p = key;
unsigned h = 0, g;
int i;
for ( i = 0; i < len; i++ ) {
h = ( h << 4 ) + p[i];
g = h & 0xf0000000L... |
The~operator is bitwiseNOT, it inverts the bits in a binary number:
```
NOT 011100
= 100011
```
|
Does Macports have Ch and Cint (C interactive interpreters) as available ports? I can't seem to find them through port search.
Failing which, can anyone recommend what is the easiest way to install either Ch or Cint on Mac OS X?
|
There is an effort by CERN developers to port their Cint to Clang: nicely namedClint.
Although I think CINT works fine on Mac: seeherefor build/install instructions
|
In creating a static object is it possible to rename the symbols at compile time (without changing the code) in a cross platform way? I have recently had objcopy recommended, but linux is not the only target platform it must also work on a mac. I am compiling using gcc, so I was hoping that there was a gcc option of s... |
is it possible to rename the symbols at compile time
You might be able to achieve it with preprocessor:
```
gcc -c foo.c -Dfoo=foo_renamed
```
|
What is the difference between Memory Profiling and Memory leak fixing in Objective C or in any Programming language?
Any help appreciated in advance, Thank You.
|
Memory Profilingis the process of determining how memory is being used by your application. This could include searching for memory leaks, but would also encompass determining how much memory non leaked objects are using.
Memory leak fixing, is specifically tracking down and fixing memory leaks. These are where you... |
I am new to Berkeley DB and learning using online guide. Now i have the following code below:
```
DB *dbp;
DBT key, data;
int ret, t_ret;
int k = 1;
key.data = &(k);
key.size = sizeof(k);
memset(&key, 0, sizeof(key));
if ((ret = dbp->put(dbp, NULL, &key, &data, 0)) == 0)
{
printf("db: %d: key stored.\n", (char*... |
Since key.data is a void*, you need to dereference it to get the value. Try:
```
printf("db: %d: key stored.\n", *(int*)key.data);
```
|
In a shift left operation for example,
5 << 1 = 10
10 << 1 = 20
then a mathematical equation can be made,
n << 1 = n * 2.
If there is an equation for a shift left operation,
then is it possible that there is also a
mathematical equation for
an AND operation?
or any other bitwise operators?
|
There is no straightforward single operation that maps to every bitwise operation. However, they can all be simulated through iterative means (or one really long formula).
```
(a & b)
```
can be done with:
```
(((a/1 % 2) * (b/1 % 2)) * 1) +
(((a/2 % 2) * (b/2 % 2)) * 2) +
(((a/4 % 2) * (b/4 % 2)) * 4) +
...
(((a/... |
Title is pretty much self-explanatory. I googled on the web and SO, and not found a satisfactory enough answer. Example:
```
FILE* oneFile = fopen( file, someflags);
FILE* sameFile = fopen( file, someflags);
```
|
C has nothing to do with it. It's all about your operating system underneath. C has no opinion.
|
I am writing a drum machine program. I need a function that takes the amount of microseconds between two sixteenth-notes as input, and outputs a beats-per-minute value. I would prefer the function to be in C.
I already have the drum machine working, but I would like a beats-per-minute representation so users can incr... |
Henning's answer is correct as to the mathematics. Here is an actual C function.
```
double GetBPMFromSixteenthDist(double nMsBetweenSixteenths)
{
return 15000000 / nMsBetweenSixteenths;
}
```
|
Given the current node, how can I find its previous node in a Singly Linked List. Thanks. Logic will do , code is appreciated. We all know given a root node one can do a sequential traverse , I want to know if there is a smarter way that avoids sequential access overhead. (assume there is no access to root node) Thank... |
You can't.
Singly-linked lists by definition only link each node to its successor, not predecessor. There is no information about the predecessor; not even information about whether it exists at all (your node could be the head of the list).
You could use a doubly-linked list.
You could try to rearrange everything s... |
I have a property, noteName, declared as follows:
```
@property (nonatomic,assign) IVNoteName noteName;
```
and defined as follows:
```
@synthesize noteName;
```
but when I attempt to use it, the static analyzer behaves strangely.
```
NSInteger noteNameOffsets[8] = {0,2,3,5,7,8,10};
midiValue += noteNameOffsets[[... |
This is no longer an issue in Xcode 4.2.
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago.
I have a doubt why it happens that ... |
Do you have an example?
The language is standardized, but a lot of aspects of it are implementation-defined or even undefined.
For example, this:
```
printf("sizeof (int) = %u\n", (unsigned)sizeof (int));
```
will print different numbers on different systems, depending on how bigintis.
|
I'm trying to establish whether Visual C++ 2008 or 2010 supports theloop unswitching compiler optimization. I know that gcc supports it.
|
AFAIK, "No":
http://cboard.cprogramming.com/c-programming/126756-lack-compiler-loop-optimization-loop-unswitching.html
Your mileage might vary, depending on:
Whether or not you have the latest compiler (MSVS 2010)Whether or not you've purchased MSVS Professional or higher
|
I have just began a new C project, using gcc (currently 4.5.2). Now, before it grows too big, I want to start unit testing it. After some googling I've realized that there are numerous of frameworks to choose from. I cannot afford testing them all.
Note that I don't mind using g++ for the unit tests, as long as I can... |
I've played with libcheck, which is pretty good. It's been a while since I last used it, but it does the job, and is just straight C.
|
I've seen the tilde operator used in the ELF hashing algorithm, and I'm curious what it does. (The code isfrom Eternally Confused.)
```
unsigned elf_hash ( void *key, int len )
{
unsigned char *p = key;
unsigned h = 0, g;
int i;
for ( i = 0; i < len; i++ ) {
h = ( h << 4 ) + p[i];
g = h & 0xf0000000L... |
The~operator is bitwiseNOT, it inverts the bits in a binary number:
```
NOT 011100
= 100011
```
|
Does Macports have Ch and Cint (C interactive interpreters) as available ports? I can't seem to find them through port search.
Failing which, can anyone recommend what is the easiest way to install either Ch or Cint on Mac OS X?
|
There is an effort by CERN developers to port their Cint to Clang: nicely namedClint.
Although I think CINT works fine on Mac: seeherefor build/install instructions
|
In creating a static object is it possible to rename the symbols at compile time (without changing the code) in a cross platform way? I have recently had objcopy recommended, but linux is not the only target platform it must also work on a mac. I am compiling using gcc, so I was hoping that there was a gcc option of s... |
is it possible to rename the symbols at compile time
You might be able to achieve it with preprocessor:
```
gcc -c foo.c -Dfoo=foo_renamed
```
|
What is the difference between Memory Profiling and Memory leak fixing in Objective C or in any Programming language?
Any help appreciated in advance, Thank You.
|
Memory Profilingis the process of determining how memory is being used by your application. This could include searching for memory leaks, but would also encompass determining how much memory non leaked objects are using.
Memory leak fixing, is specifically tracking down and fixing memory leaks. These are where you... |
I am new to Berkeley DB and learning using online guide. Now i have the following code below:
```
DB *dbp;
DBT key, data;
int ret, t_ret;
int k = 1;
key.data = &(k);
key.size = sizeof(k);
memset(&key, 0, sizeof(key));
if ((ret = dbp->put(dbp, NULL, &key, &data, 0)) == 0)
{
printf("db: %d: key stored.\n", (char*... |
Since key.data is a void*, you need to dereference it to get the value. Try:
```
printf("db: %d: key stored.\n", *(int*)key.data);
```
|
In a shift left operation for example,
5 << 1 = 10
10 << 1 = 20
then a mathematical equation can be made,
n << 1 = n * 2.
If there is an equation for a shift left operation,
then is it possible that there is also a
mathematical equation for
an AND operation?
or any other bitwise operators?
|
There is no straightforward single operation that maps to every bitwise operation. However, they can all be simulated through iterative means (or one really long formula).
```
(a & b)
```
can be done with:
```
(((a/1 % 2) * (b/1 % 2)) * 1) +
(((a/2 % 2) * (b/2 % 2)) * 2) +
(((a/4 % 2) * (b/4 % 2)) * 4) +
...
(((a/... |
Title is pretty much self-explanatory. I googled on the web and SO, and not found a satisfactory enough answer. Example:
```
FILE* oneFile = fopen( file, someflags);
FILE* sameFile = fopen( file, someflags);
```
|
C has nothing to do with it. It's all about your operating system underneath. C has no opinion.
|
I am writing a drum machine program. I need a function that takes the amount of microseconds between two sixteenth-notes as input, and outputs a beats-per-minute value. I would prefer the function to be in C.
I already have the drum machine working, but I would like a beats-per-minute representation so users can incr... |
Henning's answer is correct as to the mathematics. Here is an actual C function.
```
double GetBPMFromSixteenthDist(double nMsBetweenSixteenths)
{
return 15000000 / nMsBetweenSixteenths;
}
```
|
numCheck is number between 1-1000. This code gives me a segfault only when I collect the results of sprintf in charcheck. If I simply use sprintf without using the results, I don't get a seg fault. What's happening here?
```
char * numString;
int charcheck = sprintf(numString, "%d", numCheck);
```
|
You need to provide your own memory forsprintf. Also, don't usesprintf, but rathersnprintf:
```
char buf[1000] = {0};
snprintf(buf, 999, ....);
```
Alternatively you can allocate memory dynamically:
```
char * buf = new char[BUFSIZE];
snprintf(buf, BUFSIZE-1, ...);
/* ... */
delete[] buf;
```
|
What is the C equivalent of this C# code?
```
[StructLayout(LayoutKind.Explicit)]
struct Test
{
[FieldOffset(0)] int a; // Integer at byte offset 0
[FieldOffset(1)] int b; // Integer at byte offset 1
[FieldOffset(3)] int c; // Integer at byte offset 3
};
```
(I don't care if it's non-portable, e.g.int... |
This seems to work fine under Visual Studio:
```
#pragma pack(push)
#pragma pack(1)
typedef union
{
int a;
struct
{
char unused0;
int b;
};
struct
{
char unused1;
char unused2;
char unused3;
int c;
};
} Test;
#pragma pack(pop)
```
|
Just to make sure sure, one can call select on a Unix Domain socket. Correct? Also one can mix different types of sockets in a select statement. Is that correct?
|
Yes, that is correct. The only type of file descriptor you should not put in aselectcall is a regular file, because regular files arealwaysconsidered ready, even if reading from them would block.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
If you are talking about straight graphics look at:
SDLGGI(very simple)
If you are talking GUI,QTwould certainly be your best bet.
|
There should be something elegant in Linux API/POSIX to extract base file name from full path
|
Seechar *basename(char *path).
Or run the command "man 3 basename" on your target UNIX/POSIX system.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:Does the size of an int depend on the compiler and/or processor?
Does the size of Integer depend on Compiler or on OS or on Processor? What if I use gcc on both 32 bit OS or 64bit OS running either on 32 bit machine or 64 bit machine(only ... |
It depends on the combination of compiler, processor and OS.
For instance, on a 64 bit Intel CPU, in 64 bit mode, the size of along intin Windows is 4 byte while in Linux and on the Mac it is 8 byte.intis 4 bytes in all three OSes on Intel.
The compiler implementer also has a choice, but usually uses what the OS use... |
I don't fully understand what the following exercise is asking:
"Write a program detab that replaces tabs in the input with the proper number of blanksto space to the next tab stop. Assume a fixed set of tab stops, say every n columns.Should n be a variable or a symbolic parameter?"
Could someone clarify the bolded ... |
This exercise is asking you to emulate the behavior of tabs by adding the correct amount of spaces, such that the output is still aligned on tab stops.
For example :
```
"hello\tworld"
```
should become :
```
"hello world"
```
(the tab has been replaced with three spaces), if tab stops are every 4 columns (ie. ... |
Is it possible to Convert Int to Hexdecimal without using 'printf'?
Best if the all the value are placed in the variable itself and some sample code with explanation.
|
The decimal and hexadecimal systems are just ways of expressing the value of the int. In a way "it is already a hexadecimal".
|
In the following header file i declared some functions:
```
#ifndef _MY_INT_FUNCTIONS_H_
#define _MY_INT_FUNCTIONS_H_
int intFcn (const void *key, size_t table_size);
void intPrint (const void *key);
int intCompare (const void *key1, const void *key2);
#endif // _MY_INT_FUNCTIONS_H_
```
but ... |
In C++size_tis declared in the<cstddef>header in thestdnamespace.
```
#include <cstddef>
int intFcn (const void *key, std::size_t table_size);
```
In C (and in C++ too), it's declared in<stddef.h>:
```
#include <stddef.h>
int intFcn (const void *key, size_t table_size);
```
|
I am trying to find a way to get GCC to temporarily ignore -arch ppc and -arch i386 flags. Does anyone have a method for accomplishing this? I have read about ways to force flags, like writing shell scripts called GCC and putting them in your path above the real GCC, but I'm looking for the opposite. My want for accom... |
You could do it the same way: write a wrapper script but instead of passing all flags, go through them and remove the arch flag. This can look like this:
```
#!/bin/bash
gcc ${@/-arch=i386}
```
(here maybe some fine tuning is necessary: when you have to remove multiple options introduce a help variable and make the ... |
Could you please make it clear what the difference is betweenunsignedandunsigned int? Maybe some example code would be helpful.
|
unsignedis a modifier which can apply to any integral type (char,short,int,long, etc.) but on its own it is identical tounsigned int.
|
numCheck is number between 1-1000. This code gives me a segfault only when I collect the results of sprintf in charcheck. If I simply use sprintf without using the results, I don't get a seg fault. What's happening here?
```
char * numString;
int charcheck = sprintf(numString, "%d", numCheck);
```
|
You need to provide your own memory forsprintf. Also, don't usesprintf, but rathersnprintf:
```
char buf[1000] = {0};
snprintf(buf, 999, ....);
```
Alternatively you can allocate memory dynamically:
```
char * buf = new char[BUFSIZE];
snprintf(buf, BUFSIZE-1, ...);
/* ... */
delete[] buf;
```
|
What is the C equivalent of this C# code?
```
[StructLayout(LayoutKind.Explicit)]
struct Test
{
[FieldOffset(0)] int a; // Integer at byte offset 0
[FieldOffset(1)] int b; // Integer at byte offset 1
[FieldOffset(3)] int c; // Integer at byte offset 3
};
```
(I don't care if it's non-portable, e.g.int... |
This seems to work fine under Visual Studio:
```
#pragma pack(push)
#pragma pack(1)
typedef union
{
int a;
struct
{
char unused0;
int b;
};
struct
{
char unused1;
char unused2;
char unused3;
int c;
};
} Test;
#pragma pack(pop)
```
|
Just to make sure sure, one can call select on a Unix Domain socket. Correct? Also one can mix different types of sockets in a select statement. Is that correct?
|
Yes, that is correct. The only type of file descriptor you should not put in aselectcall is a regular file, because regular files arealwaysconsidered ready, even if reading from them would block.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
If you are talking about straight graphics look at:
SDLGGI(very simple)
If you are talking GUI,QTwould certainly be your best bet.
|
There should be something elegant in Linux API/POSIX to extract base file name from full path
|
Seechar *basename(char *path).
Or run the command "man 3 basename" on your target UNIX/POSIX system.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:Does the size of an int depend on the compiler and/or processor?
Does the size of Integer depend on Compiler or on OS or on Processor? What if I use gcc on both 32 bit OS or 64bit OS running either on 32 bit machine or 64 bit machine(only ... |
It depends on the combination of compiler, processor and OS.
For instance, on a 64 bit Intel CPU, in 64 bit mode, the size of along intin Windows is 4 byte while in Linux and on the Mac it is 8 byte.intis 4 bytes in all three OSes on Intel.
The compiler implementer also has a choice, but usually uses what the OS use... |
I don't fully understand what the following exercise is asking:
"Write a program detab that replaces tabs in the input with the proper number of blanksto space to the next tab stop. Assume a fixed set of tab stops, say every n columns.Should n be a variable or a symbolic parameter?"
Could someone clarify the bolded ... |
This exercise is asking you to emulate the behavior of tabs by adding the correct amount of spaces, such that the output is still aligned on tab stops.
For example :
```
"hello\tworld"
```
should become :
```
"hello world"
```
(the tab has been replaced with three spaces), if tab stops are every 4 columns (ie. ... |
Is it possible to Convert Int to Hexdecimal without using 'printf'?
Best if the all the value are placed in the variable itself and some sample code with explanation.
|
The decimal and hexadecimal systems are just ways of expressing the value of the int. In a way "it is already a hexadecimal".
|
In the following header file i declared some functions:
```
#ifndef _MY_INT_FUNCTIONS_H_
#define _MY_INT_FUNCTIONS_H_
int intFcn (const void *key, size_t table_size);
void intPrint (const void *key);
int intCompare (const void *key1, const void *key2);
#endif // _MY_INT_FUNCTIONS_H_
```
but ... |
In C++size_tis declared in the<cstddef>header in thestdnamespace.
```
#include <cstddef>
int intFcn (const void *key, std::size_t table_size);
```
In C (and in C++ too), it's declared in<stddef.h>:
```
#include <stddef.h>
int intFcn (const void *key, size_t table_size);
```
|
I am trying to find a way to get GCC to temporarily ignore -arch ppc and -arch i386 flags. Does anyone have a method for accomplishing this? I have read about ways to force flags, like writing shell scripts called GCC and putting them in your path above the real GCC, but I'm looking for the opposite. My want for accom... |
You could do it the same way: write a wrapper script but instead of passing all flags, go through them and remove the arch flag. This can look like this:
```
#!/bin/bash
gcc ${@/-arch=i386}
```
(here maybe some fine tuning is necessary: when you have to remove multiple options introduce a help variable and make the ... |
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
If you are talking about straight graphics look at:
SDLGGI(very simple)
If you are talking GUI,QTwould certainly be your best bet.
|
There should be something elegant in Linux API/POSIX to extract base file name from full path
|
Seechar *basename(char *path).
Or run the command "man 3 basename" on your target UNIX/POSIX system.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:Does the size of an int depend on the compiler and/or processor?
Does the size of Integer depend on Compiler or on OS or on Processor? What if I use gcc on both 32 bit OS or 64bit OS running either on 32 bit machine or 64 bit machine(only ... |
It depends on the combination of compiler, processor and OS.
For instance, on a 64 bit Intel CPU, in 64 bit mode, the size of along intin Windows is 4 byte while in Linux and on the Mac it is 8 byte.intis 4 bytes in all three OSes on Intel.
The compiler implementer also has a choice, but usually uses what the OS use... |
I don't fully understand what the following exercise is asking:
"Write a program detab that replaces tabs in the input with the proper number of blanksto space to the next tab stop. Assume a fixed set of tab stops, say every n columns.Should n be a variable or a symbolic parameter?"
Could someone clarify the bolded ... |
This exercise is asking you to emulate the behavior of tabs by adding the correct amount of spaces, such that the output is still aligned on tab stops.
For example :
```
"hello\tworld"
```
should become :
```
"hello world"
```
(the tab has been replaced with three spaces), if tab stops are every 4 columns (ie. ... |
Is it possible to Convert Int to Hexdecimal without using 'printf'?
Best if the all the value are placed in the variable itself and some sample code with explanation.
|
The decimal and hexadecimal systems are just ways of expressing the value of the int. In a way "it is already a hexadecimal".
|
In the following header file i declared some functions:
```
#ifndef _MY_INT_FUNCTIONS_H_
#define _MY_INT_FUNCTIONS_H_
int intFcn (const void *key, size_t table_size);
void intPrint (const void *key);
int intCompare (const void *key1, const void *key2);
#endif // _MY_INT_FUNCTIONS_H_
```
but ... |
In C++size_tis declared in the<cstddef>header in thestdnamespace.
```
#include <cstddef>
int intFcn (const void *key, std::size_t table_size);
```
In C (and in C++ too), it's declared in<stddef.h>:
```
#include <stddef.h>
int intFcn (const void *key, size_t table_size);
```
|
I am trying to find a way to get GCC to temporarily ignore -arch ppc and -arch i386 flags. Does anyone have a method for accomplishing this? I have read about ways to force flags, like writing shell scripts called GCC and putting them in your path above the real GCC, but I'm looking for the opposite. My want for accom... |
You could do it the same way: write a wrapper script but instead of passing all flags, go through them and remove the arch flag. This can look like this:
```
#!/bin/bash
gcc ${@/-arch=i386}
```
(here maybe some fine tuning is necessary: when you have to remove multiple options introduce a help variable and make the ... |
Could you please make it clear what the difference is betweenunsignedandunsigned int? Maybe some example code would be helpful.
|
unsignedis a modifier which can apply to any integral type (char,short,int,long, etc.) but on its own it is identical tounsigned int.
|
There is supposedly something wrong (in terms of software security) with this code snippet and i cant seem to figure it out ...The function die terminates the the program after displaying the string argument.
```
void get_user(char* user)
{
char buf[1024];
if (strlen(user) > sizeof(buf))
die("error: user stri... |
It is not counting the NUL (\0) terminator for the string.
```
if (strlen(user) >= sizeof(buf))
```
It's unsafe ifuserhas 1024 characters (will write0somewhere on the stack).
|
I came across this puzzlehere. I can't figure out whyNONEis not printed. Any ideas?
```
#include<stdio.h>
int main()
{
int a=10;
switch(a)
{
case '1':
printf("ONE\n");
break;
case '2':
printf("TWO\n");
... |
defa1ut:is a syntactically valid label, e.g. for agotobut not thedefaultof the switch statement.
If you compile with gcc with enough warnings it will point this out:
ajw@rapunzel:/tmp > gcc -Wall -Wextra test.ctest.c: In function ‘main’: test.c:13:15: warning: label ‘defa1ut’
defined but not used
It's a good argu... |
I am using OpenSolaris on x86. I tried the gcc compiler for Solarisfor free, but found it to be quite old (gcc 3.4.6). I want to know if there is any latest C++ compiler for OpenSolaris, that is similar to gcc. What is the best compiler out there for x86 with Solaris?
|
Nothing is more similar to GCC than GCC... The GNU people have some answers for you:
http://gcc.gnu.org/install/binaries.html
If none of those binaries are useful, Google found for me:
http://www.dev-eth0.de/compile-gcc-4-on-opensolaris
Why haven't you found a good guide like that and run with it? It's not all tha... |
Why does this program below not show any error ?
```
int main (void) {
"ANGUS";
1;
3.14;
return 0;
}
```
|
Each of those statements are expressions that evaluate to a value, which is then discarded.
Compare it to if you called a function that returned an int, a char or a float, without using the return value. That's also an expression that evaluates to a value.
It is not uncommon to have functions that return values that ... |
Scenario 1:
Code:
```
int main(){
int a = 12345678;
if(isdigit(a)){
printf("ok: foo\n");
}
else{
printf("false: bar\n");
}
printf("test\n");
return EXIT_SUCCESS;
}
```
Output:
```
Segmentation fault
```
Scenario 2:
Code:
```
...
if(isdigit(a)){
//printf("o... |
Probably because the compiler optimizes the isdigit function call from the code. That is it doesn't run it.
Also note that isdigit expects a character, not a number.http://www.cplusplus.com/reference/clibrary/cctype/isdigit/
|
I have a basic pointer question.
I have some code like this:
Please let me know if anything is wrong in the following code:
```
struct abc {
int a;
int b;
};
void func2(int*); // defined elsewhere
void func1 (struct abc *p1)
{
struct abc var1 = *p1; // ======> Can I do this ?
func2(&var1.b);
func2(&p1->... |
struct abc var1 = *p1;======> Can I do this ?
Yes, this copies the struct pointed by p1 in the local variable var1.
func2(&var1.b);func2(&p1->b);=========> Which of these 2 is right ?
Both, iffunc2()accepts aint*as parameter. It depends if you wantfunc2to modifyp1->borvar1.b.
|
http://www.freebsd.org/cgi/cvsweb.cgi/src/contrib/tar/lib/Attic/getdate.c?hideattic=0
Revision 1.2
Fri Sep 15 08:04:20 2006 UTC (4 years, 11 months ago) by ru
Branches: MAIN
CVS tags: HEAD
FILE REMOVED
Changes since revision 1.1: +0 -0 linesRemove vestiges of GNU tar.
What does this mean?getdate.chas been ... |
it means the gnu tar version has been removed from the FreeBSD source tree in favor of a BSD-licensed one aka bsdtar (which works very nicely). This means of course that it does not belong in contrib anymore and has been moved to here:http://www.freebsd.org/cgi/cvsweb.cgi/src/usr.bin/tar/?hideattic=0
|
So basically what i need is:
```
pid = fork();
if (pid == -1)
exit(1);
if (pid == 0)
{
// do stuff in child
}
else
{
// ONLY do stuff while child is running
}
```
would I need to create a tmp file right before the child exits saying that it is no longer running so the parent knows the child has exited when... |
You can usewaitpidto know if a child process is still running:
```
int status;
if (waitpid(pid, &status, WNOHANG) == 0) {
// still running
}
```
WithWNOHANG,waitpidreturns immediately so that the program can do something else.
When you have nothing to do other than waiting for the child process to terminate, ca... |
For a low end embedded microcontroller (8-bit), which timestamp structure would be smallest? I'm considering custom ones too. Because of computing power is very limited, it's also important to reading second, hour, or day etc. should be fast too.
This questioncovers my question, but i need to represent next minimum 1... |
i need to represent next minimum 10 years with resolution of second
If you use anint32_tyou're good until 2038 with these timestamps, and withuint32_tyou can cover until 2106. Usinglocaltime,gmtimeand such you can convert them intostruct tmif you need and extract the day, month etc.
|
So recently I got into a debate about how to solve a problem, the problem specifically was: How do I find all the pallindromes between 1 and 1 million. I said, "Use atoi to make a string, use a for loop to reverse the string, the use strcmp to compare the string(s) in question.
A few minutes later someone asked "Wh... |
Quite simply, C++ streams are guaranteed to be memory safe and exception safe, failure is distinct from any return value, and C++ strings are memory-safe and exception-safe. C-strings andatoiare hideously unsafe in pretty much every way known to man. Code written in that way is much more error-prone.
|
When I want to print a hexadecimal value of an integer using printf in C, I use the following statement :printf ("\n X = 0x%x \n",x);Here I assume the following declaration :int x = -1
Now this printsOxffffffff. I would like to see the output as 0xFFFFFFFF (all Tall Letters). Which format specifier will help me achie... |
printf ("\n X = 0x%X \n",x);
|
I am developing MFC Dialog based application in Visual Studio 2008. I want to use timer that start on start of the application and continue to run and calls a function that performs my task? How can I do this?
Thanks
|
Just useSetTimermethod, and pass two arguments: Timer ID (any number), and the timeout in milliseconds. Then write upOnTimerimplementation, and an entryON_WM_TIMERinsideBEGIN_MESSAGE_MAP...END_MESSAGE_MAP.
CWnd::SetTimertakes 3 parameters, but only 2 are required. Pass third argument as NULL.
CWnd::OnTimer
|
Is there an official reference listing the operation of the SSE intrinsic functions for GCC, i.e. the functions in the <*mmintrin.h> header files?
|
As well as Intel's vol.2 PDF manual, there is also anonline intrinsics guide.
The Intel® Intrinsics Guide contains reference information for Intel intrinsics, which provide access to Intel instructions such as Intel® Streaming SIMD Extensions (Intel® SSE), Intel® Advanced Vector Extensions (Intel® AVX), and Intel® Ad... |
For a low end embedded microcontroller (8-bit), which timestamp structure would be smallest? I'm considering custom ones too. Because of computing power is very limited, it's also important to reading second, hour, or day etc. should be fast too.
This questioncovers my question, but i need to represent next minimum 1... |
i need to represent next minimum 10 years with resolution of second
If you use anint32_tyou're good until 2038 with these timestamps, and withuint32_tyou can cover until 2106. Usinglocaltime,gmtimeand such you can convert them intostruct tmif you need and extract the day, month etc.
|
So recently I got into a debate about how to solve a problem, the problem specifically was: How do I find all the pallindromes between 1 and 1 million. I said, "Use atoi to make a string, use a for loop to reverse the string, the use strcmp to compare the string(s) in question.
A few minutes later someone asked "Wh... |
Quite simply, C++ streams are guaranteed to be memory safe and exception safe, failure is distinct from any return value, and C++ strings are memory-safe and exception-safe. C-strings andatoiare hideously unsafe in pretty much every way known to man. Code written in that way is much more error-prone.
|
When I want to print a hexadecimal value of an integer using printf in C, I use the following statement :printf ("\n X = 0x%x \n",x);Here I assume the following declaration :int x = -1
Now this printsOxffffffff. I would like to see the output as 0xFFFFFFFF (all Tall Letters). Which format specifier will help me achie... |
printf ("\n X = 0x%X \n",x);
|
I am developing MFC Dialog based application in Visual Studio 2008. I want to use timer that start on start of the application and continue to run and calls a function that performs my task? How can I do this?
Thanks
|
Just useSetTimermethod, and pass two arguments: Timer ID (any number), and the timeout in milliseconds. Then write upOnTimerimplementation, and an entryON_WM_TIMERinsideBEGIN_MESSAGE_MAP...END_MESSAGE_MAP.
CWnd::SetTimertakes 3 parameters, but only 2 are required. Pass third argument as NULL.
CWnd::OnTimer
|
Is there an official reference listing the operation of the SSE intrinsic functions for GCC, i.e. the functions in the <*mmintrin.h> header files?
|
As well as Intel's vol.2 PDF manual, there is also anonline intrinsics guide.
The Intel® Intrinsics Guide contains reference information for Intel intrinsics, which provide access to Intel instructions such as Intel® Streaming SIMD Extensions (Intel® SSE), Intel® Advanced Vector Extensions (Intel® AVX), and Intel® Ad... |
So I built the linux kernel tags using the make tags command but for some reason when opening the tags file in emacs (for tag lookups) first it asks if I really want to open the file (which makes sense because the file is a 66mb tag file so that's a lot of definitions) and then after it tries to load it it tells me th... |
Check the makefile and see if make tags uses ctags instead of etags. If it does, you may need to do some editing to make it use etags.
To generate a tag file for use within Emacs you have to launch the commandmake TAGSinstead ofmake tagsas you did. That is, the uppercase «TAGS» option will generate the etags table.
|
So i have two structs in the global section
```
typedef struct stack_1
{
short ctr;
} stack_1;
typedef struct stack_2
{
struct stack_1 *s1;
} stack_2;
```
then later in the code i do
```
struct stack_2 *x;
```
what is my x initialized to ?? 0 or Null. Thank you in advance.
|
If your declaration is outside any function or with thestatickeyword (more precisely, has static storage duration), the initial value of x is a null pointer (which may be wrtten either as0or asNULL). If it's inside a function (more precisely, has automatic storage duration), its initial value is garbage.
|
I am working on the DES (Data Encryption Standard) algorithm in my Cryptography class, as a part of which I have to write a C code which includes a function to check the parity of a DES key.
How can I do this?
|
I would just do aGoogle search, and pickone of the first results that comes up.
Taken from the above link:
```
bool AdjustDESKeyParity(UCHAR* pucKey, int nKeyLen)
{
int cPar;
for(int i = 0; i < nKeyLen; i++)
{
cPar = 0;
for(int j = 0; j < DES::BLOCKSIZE; j++)
{
if(pucKey[i] & (0×0... |
In a comment to thisansweronthe usage of Anonymous enum,Oli Charlesworthstates that:
const int is immutable, and may not take up any space, depending on
what the compiler chooses to do.
If I declareconst int i = 10, how is that10stored if it "may not take up any space"?
Assuming that anintis 4 bytes, I would pres... |
The compiler is free to optimise code as it sees fit, so long as the resulting code offers the same observable side effects.
So variables may be optimised to only exist in registers, or replaced with immediate values. In pseudo-machine-code:
```
SET 10, eax
ST eax, &i # Initialise i
...
LD &i, eax # Add i t... |
Givenunsigned char *str, a UTF-8 encoded string, is it legal to write the first byte (not character) withfputc((char)(*str), file);
|
Remove the cast tochar.fputctakes the character to write as anintargument whose value is expected to be in the range ofunsigned char, notchar. Assuming(unsigned char)(char)acts as the identity operator onunsigned charvalues, there's no error in your code, but it's not guaranteed to especially for oddball systems witho... |
```
struct str {
uint8_t *data;
};
int main() {
struct str *buffer;
free(buffer->data);
}
```
How to right check data before use free ? This example call Segmentation failed ...
|
This is because your data has not been allocated. You only create a pointer on a struct str. The correct use is the following:
```
int main() {
struct str *buffer = (struct str*)malloc(sizeof(struct str));
if (buffer == NULL) { fprintf(stderr, "Error with malloc\n"); exit (EXIT_FAILURE); }
buffer->data = (uint8... |
How does one explain:
```
int main()
{
unsigned char z=-1;
printf("%u %d",z,z);
}
```
gives 255 255?
|
It's not about the specifiers, it's about the type - it'sunsigned. As the range is[0;255]forunsigned charand(unsigned xxx)-1by standard, means - give the max value for unsigned xxx type.
Your code:
```
unsigned char z=-1;
```
has implicit conversion and it's the same as
```
unsigned char z= (unsigned char)-1;
``... |
```
int main(int argc, char** argv) {
int i = 0;
while (i < 2) {
fork();
system("ps -o pid,ppid,comm,stat");
i++;
}
return (EXIT_SUCCESS);
}
```
Can anyone tell me how many times ps command is executed with an explanation?
|
I believe the answer is 6.
in the first iteration,fork()is called, splitting the process in 2, thus calling ps twice.
in the second iteration, fork is called again in each process, so you now have 4 processes running ps.
total calls to ps: 2+4=6.
|
can any one tell me why the following code always return 0 . the socket descriptor value is 3.
i am using the open suse TFTP server . which is listening on port 69 in Local host.
connect() function return success ..
```
connection_timer.tv_sec = 2; // s
connection_timer.tv_usec = 0;
FD_ZERO(&fd_reader);
/... |
You will get a return code of0fromselectit the timer (connection_timerin your example) expires before any descriptor has become interesting.
So it's not an error. It seems most likelyyou didn't initializeconnection_timerproperly.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.