question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I am getting the following compilation / link error:
```
ld: 0711-317 ERROR: Undefined symbol: .__gcc_qsub
ld: 0711-317 ERROR: Undefined symbol: .__gcc_qmul
ld: 0711-317 ERROR: Undefined symbol: .__gcc_qadd
```
What library holds those?
Any ideas?
Lynton
|
Here's a total stab in the dark...
A Google search picked upthis header from Apple. It looks like its part oflibgcc(which is not Apple specific, that's just Apple's implementation), and that its used for doinglong doublearithmetic in software. Try adding-lgccto your build process.
According to the GCC manual, you ca... |
```
#include<stdio.h>
int main()
{
printf("%x",-2<<2); //left shift of a negative integer
return 0;
}
```
If negative integers are represented with a sign bit, then I fear the sign bit will be lost.
Please explain a bit.
|
The behaviour is at best 'implementation defined', and possibly 'undefined behaviour'.
|
I have a multithreaded program and in the code below, when the value of y becomes less than 0, I need all the threads to stop running.
Here's the source code -
```
else if(y<0)
{
flag=1;
printf("Exit the program\n");
pthread_exit((void *)55);
printf("sdjfajdfl... |
pthread_exitexits the current thread, not others. I believeexitshould exit all threads.
|
As I registered the my object as a property listener. Is it necessary for me to perform any sort of "unlistening" before I release the object.
|
You should not continue to observe objects you are not retaining (this applies to KVO, delegation, notification, any any other listener pattern). Here is the danger:
You observe an object ("observed") and retain it.Some other object also retains "observed"You release "observed"You deallocate"observed" changes a prope... |
Do -fstack-protector and -fstack-protector-all protect heap-based memory allocations too or only stack-based ones ?
What is the difference between the first 2 and -fmudflap ?
Any recommendations as to which is better for debugging ?
(I'm not sure if thegcc man pageis clear enough or I simply do not understand it...... |
-fstack-protector and -fstack-protector-all have nothing to do with heap allocations.-fstack-protector protects strings only (main problem target for buffer overflow attacks), -fstack-protector-all protects all types. Some descriptions here:http://en.wikipedia.org/wiki/Buffer_overflow_protection
|
I have a clutter texture as my background . I need to put some clutter actors over it. is it possible to do it . Since i get the following error:
```
"invalid cast from `ClutterTexture' to `ClutterContainer' "
```
Can any one help me ?
|
ClutterTexture is not a container, i.e. it cannot contain other actors.
ClutterBox and ClutterGroup are containers available in Clutter; ClutterBox allows using different layout managers - like ClutterBinLayout:
http://developer.gnome.org/clutter/stable/ClutterBinLayout.html
or ClutterFixedLayout:
http://developer... |
I have written a windows service in C. I would like to install/uninstall it without using .NET framework (installutil) or a visual studio installer (because I'm writing this in C).
I am using NSIS to install my application which contains this service among many other things. Can NSIS install/uninstall windows servic... |
TheNSIS documentation lists the various possibilities. You simply need to pick the one most suitable to your needs.
It's much easier to get NSIS to do this than to script it yourself by calling the service control manager API.
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago.
I want to apply<<shifting operator ... |
I'm not really sure I understand what you want to do, but if you want to do:
```
*(p+i) = *(p+i) << 1;
*(p+i) = *(p+i) + 1; //++
```
You can rewrite them as:
```
*(p+i) <<= 1;
*(p+i) += 1;
```
|
I want to be able to check to see if a file could be opened on Linux (for read or for read and write). However I don't have control of the code which will be opening the file, so I can't do what I would normally do which is to open it and then handle the error.
I appreciate that there will always be race conditions o... |
You can use:
```
access("filename", R_OK);
```
or
```
euidaccess("filename", R_OK);
```
To check if your UID or EUID have read access to a respective file. (UID and EUID will be different if your are running setuid)
|
```
#include <stdio.h>
#include <stdbool.h>
int main()
{
bool a[5]={0,1,0,0,0};
a[1]=3;
printf("\n bool is %d",a[1]);
printf("\n sizeof bool is %d and size of a is %d",sizeof(bool),sizeof(a));
bool b[10];
printf("\n bool is %d",b[1]);
}
```
output of this program is
```
bool is 1
sizeof bool is 1 and size of a i... |
1> Bool store is not 1 bit. Nothing is 1 bit. Everything is at least 1 byte.sizeof(bool)is platform specific. Onlysizeof(char)is guaranteed to be 1.
2> It implicitly convertsinttobool:(bool)3 == 1
3> the arraybis not initialized, it can have any value. You're just accessing some memory.
|
Let's say you have:
```
void *a = //some address;
*((int **)(char*)a) = 5
```
I'm not really clear on what the second line is supposed to be doing... I know that 'a' is casted to a pointer to a char, and then eventually casted to a pointer to a pointer to an int, but it was unclear what dereferencing a pointer t... |
it is storing the value 5 in "some address", but more precisely, it is storing the value 5 widened to the machine address size in those many bytes starting at "some address".
e. g. if it is a 64-bit machine, it is storing the value 0x0000000000000005 at the 8 bytes starting at "some address"
i don't see why it is do... |
Is it possible to create a function from struct?
Like this:
```
#include <stdio.h>
struct dma
{
int day, mes, year;
};
dma *x(int a, int b, int c)
{
}
int main(int argc, char *argv[])
{
}
```
and, this function return an struct..
If possible, how can I use them?
|
Not sure what you want to accomplish, but perhaps this is close enough?
```
struct dma
{
int day, mes, year;
};
struct dma *x(int a, int b, int c)
{
struct dma *res = (struct dma *)malloc(sizeof(struct dma));
res->day = a;
res->mes = b;
res->year = c;
return res;
}
int main(int argc, char *a... |
I have one charater pointer array which points to the some stirngs
every element points to some strings
one thing in mind strings have only 1 and 0 .
for example
i have character pointer that stores string like "100110" so its takes 6 bytes to store but i want to store this in bits so i reduce memory occpuied.
|
In C style, something like this should work:
```
char* str = "100101";
unsigned out = 0;
for (int i = 0; str[i]; i++) {
out = (out << 1);
if (str[i] == '1')
out++;
}
```
(I cannot test this for now, so please correct me if I'm wrong)
Explanation:
```
str = "100101"
out = 0000 0000 0000 0000
i = 0:
... |
Let's say you have a "void *a" and "void *ptr" that point to different addresses defined in your code. Then I was wondering if these two lines were equivalent and functionally the same?
```
*((unsigned **)((char*)ptr+4)) = a;
```
and
```
*((unsigned *)((char*)ptr+4)) = a;
```
The second one throws a warning that "... |
These are not equivalent. #1 resolves(char*)ptr+4to be a pointer to unsigned (*unsigned), while #2 resolves it to beunsigned.
ais a void pointer, so it can be casted to*unsigned, but not tounsigned(implicitly), that's why you get the warning.
The #3 resolves the same to achar, which would also yield a warning.
|
Hello every one this is basically extension to my previous question. i have write the short int value in file using
```
short int x= 254;
FILE * f1 = fopen("infile" ,"w");
fwrite (&x , 1 , sizeof(short int ) , f1 );
```
it working fine but when i tried to retrieve value like this
```
short int y ;
fread(&y , 2, 1 ,... |
Most likey you aren't closing and reopening the file between writing and reading. I would suggest creating a small function that does both actions, first writing, then closing and flushing, then reading. See what kind of results you get with that. Also, make sure you are using binary mode.
|
I am converting an existing multi-target Silverlight/.NET project to a Portable Class Library project in order to reduce the number of projects that are required to support multiple Microsoft platforms.
I have an error in one class that is using the System.Security.Cryptography namespace
The type or namespace name '... |
No unfortunately, Portable Library does not support Crypto. However, we've added support for it inPclContrib.
|
I want to start at a particular offset, write and then at some point read from that same offset and confirm I read what I wrote to the file. The file is in binary. I'm confident I need to use fseek but I may want to call a write several times prior to reading the whole file.
```
write(unsigned long long offset, void*... |
You can useftell()to tell you your current position in the file, perform some writes and thenfseek()to the starting position you got with ftell() to read the data that you wrote.
|
I am new in C programming language and have an (if statement) and need to transfer it into switch statement.
My problem is that I have a field named (node_kind) of char* type and I compare it's content in the if statement using (strcmp) but I don't know how to do that in the switch statement.
Would you plz tell me how... |
In C you can only use integer literal constants in switch case labels.
For the code example above though, you ought to think about using a "data driven" approach rather than hard-coding all this stuff into the program logic.
|
I know how to create ajobjectand would like to convert an existingchar **into a correspondingbyte[][]and pass it to thejobjectusing JNI.
How would I go about doing it?
|
Thishttp://java.sun.com/developer/onlineTraining/Programming/JDCBook/jnistring.htmldescribes the about Multi-Dimensional Arrays in JNI
|
What will be the output of the following program?
```
int *call();
void main() {
int *ptr = call();
printf("%d : %u",*ptr,ptr);
clrscr();
printf("%d",*ptr);
}
int *call() {
int x = 25;
++x;
//printf("%d : %u",x,&x);
return &x;
}
```
Expected Output: Garbage valueActual Output: 26 #someaddr
Since x... |
itsUndefined behaviour
since at x scope is dead after returning from call() so the pointer to that variable you can not use ahaed
BY COMPILING YOUR program you will get following error
```
warning: function returns address of local variable
```
if your program since give output 26 since its undefined behaviour. Yo... |
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed10 years ago.
Consider:
```
int m = 2, n;
n = m++ + (++m);
```
In C output is:
```
m = 4, n = 4;
```
In Java output is:
```
m = 4, n = 5;
```
How does this happen?
|
It can differ because C does not allow a correct program to contain such an expression - C does not define the behaviour of such a program. This gives C compilers wide latitude in how they interpret such expressions.
Java more tightly constrains implementations by defining the expected behaviour of expressions like ... |
I am currently usingdlmalloc()to see how much faster it can be than the original libcmalloc().
However, runningfree()keeps giving me a segmentation fault...
Does anyone know some logical reasons why this could keep happening?
|
A segfault inside the memory management functions almost always indicates that you've done something wrong (like overwriting memory beyond the valid bounds)beforethe call that actually segfaults.
Running your code underValgrindmay help you determine the real source of the problem.
|
I am interested if there is any way to set default way to input numbers in C, for example xxxx.xx, like valid number for this example would be 1.00 or 1234.00, something like that.
I have searched for this in many sites, but didn't find anything useful.
I know its rather simple task, but I am new forCso it gives m... |
If I understand your question correctlyscanf()may be what you're looking for.
scanf() C reference
With that function you can define the format of the input fromstdin.
```
float f;
scanf ("%f",&f);
```
type:e,E,f,g,GFloating point:Decimal number containing a decimal point, optionally
preceded by a + or - sign and... |
I know you can get the first byte by using
```
int x = number & ((1<<8)-1);
```
or
```
int x = number & 0xFF;
```
But I don't know how to get the nth byte of an integer.
For example, 1234 is 00000000 00000000 00000100 11010010 as 32bit integer
How can I get all of those bytes? first one would be 210, second would ... |
```
int x = (number >> (8*n)) & 0xff;
```
where n is 0 for the first byte, 1 for the second byte, etc.
|
The following is the source code:
```
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
double x;
clrscr();
printf("Enter angle:");
scanf("%lf",&x);
printf("Sine %lf = %lf",x,sin(x));
getch();
}
```
Can anyone tell me what is wrong?
|
Maybe there is 3 issues with the code:
You should convertxto radian angle :sin(x*3.14159265/180.0).You should add\n:printf("Sine %lf = %lf\n",x,sin(x*PI 3.14159265/180.0));Because it flushes output tostdout.Maybe you have a compile error withclrscr()which is not supportet with currently compilers.
So try this:
```
... |
I want to match a group recursively using PCRE C library.
e.g.
```
pattern = "(\d,)"
subject = "5,6,3,2,"
OVECCOUNT = 30
pcrePtr = pcre_compile(pattern, 0, &error, &erroffset, NULL);
rc = pcre_exec(pcrePtr, NULL, subject, (int)strlen(subject),
0, 0, ovector, OVECCOUNT);
```
rc is -1..
How to match all groups so ... |
Any way I used strtok since "," was repeating after each group..
Solution using pcre is welcomed....
|
I got text file with information:(100;200;first).Can anybody tell me how to seperate this information into three arrays:Min=100,Max=200 and Name=first. I have tried this whith
c=getc(inp);
i=atoi(szinput);
but its read 10 for first time and 00 for second... and so on in loop
c saves 10 not 1, so i cant get the rig... |
usescanforfscanflike this:
```
scanf("(%d;%d;%[^)])",&min,&max,str);
```
|
When I was browsing the Linux code I encountered the following snippet :
```
static void __init do_initcalls(void)
{
initcall_t *fn;
for (fn = __early_initcall_end; fn < __initcall_end; fn++)
do_one_initcall(*fn);
}
```
initcall_tis a function pointer .
The prototype ofdo_initcallsisint do_one_initcall(initcal... |
Becauseinitcall_tis itself defined as a function pointer,initcall_t *fndeclares a pointer to a function pointer, and thus the*dereferencing operator is applied to get the function pointer.
Here is the definition of theinitcall_ttype:
```
typedef int (*initcall_t)(void);
```
So the typeinitcall_tis already a pointer... |
I am trying to write a simple shell which accepts command line input and execute it as a background task.
How do I allow the child process to report to the parent process once it is completed, like the Bash shell?
```
user@user-desktop:~$ sleep 10 &
[1] 3729
user@user-desktop:~$ sleep 2 &
[2] 3730
user@user-desktop:... |
Since this is your homework, I won't give you full answer.
TheGNU Glibc manuallist the requirnment for job control shell. Let's see if you can understand it.
Basically:
you have to change the control terminal to make jobs run in backgroundyou have to handleSIGCHLD(orwait) to monitor jobs
Ask again after you have r... |
I'm trying to subtract strings where each ASCII character is treated as a decimal digit. For instance:
```
"1000000000001" - "0100000000001" = "900000000000"
```
How would I get started on an implementation of this if my function prototype looked like:
char* get_sub(char* a, char* b)
|
Just remember how you learned to do subtraction of large numbers in your Algorithms 001 class, the primary school. Subtract the least significant digits of both numbers, add 10 if smaller than 0, remember carry, go on to next digit pair.
|
I've got a problem with windows consoles... In windows api, does aconsolealways has to be a screen or a keyboard or can it be any character buffer or something like a text file ?
thanx
If I be more specific,SetConsoleModefnction in windows api has a parameter calledhConsoleHandlewhich has a flag calledENABLE_ECHO_IN... |
No, a "console" implies an application that has a text-based interface.
Win32 Consoleon Wikipedia says that that label specifies a text mode program that runs under the Windows API, and would use, for example, a function likeWriteConsoleinstead ofprintforcout.
So, the console's the same, but the underlying library i... |
Why is050not equal to50in the following snippet?
```
#include <stdio.h>
int main(void) {
int x=050,y=50;
int ans;
ans= x==y ? x+3 : y+7;
printf("%d\n",ans);
}
```
|
Because050is considered octal and50is considered decimal.
Sox = 050basically meansx = 40.
6.4.4.1/3Adecimal constant begins with a nonzero digitand consists of a
sequence of decimal digits.An octal constant consists of the prefix 0optionally followed by a sequence of the digits 0 through 7 only.
|
Have a simple while loop and trying to make it to a for loop
```
i=1
while(i<=128)
{ printf("%d",i);
i*=2;
}
```
Here is my for loop
```
for (i=1;i<=128;i++)
{
printf("%d",i);
i*=2;
}
```
How come it does not give the same output? The first one would print1248163264128, the for loop print137153163127... |
Theforloop doublesiand then increments it. Thewhileloop only doubles it.
Change theforloop to this:
```
for (i=1;i<=128;i*=2) {
printf("%d", i);
}
```
|
Can some one explain to me the out put of this simple code segment?
```
int i=7;
int j=3*i-- + 2;
printf("%d %d",i,j)
```
When I compile I get6,23.
How does it come to 23? I thought it would be 3*7=21 decrease to 20 and added 2 is 22 not 23?
|
```
int i = 7; /* i is 7 */
int j = (3 * (i--)) /* means 3 * 7 */ + 2; /* 3 * 7 + 2 = 23 */
/* i is now 6, because it was decreased by the postfix -- operator */
printf("%d %d", i /* 6 */, j /* 23 */);
```
|
Having the signature of the function :
```
int my_print(const char *format, ...);
```
I want to implement it by callingprintfwith arguments passed tomy_printandfflush(stdout);
What do you think the best way to implement it?
|
You can usevprintf. It accepts ava_list, which is what you get inmy_print:
```
int my_print(char * format, ...)
{
va_list args;
va_start (args, format);
int ret = vprintf (format, args);
va_end (args);
return ret;
}
```
|
If I make adupof thestdoutstream (in order to use it later) and makefreopenof thestdoutstream to the file and thenprintf("data"), the file is not updated immediately with data. It is updated only after I performfflush(stdout).
Does thefflush(stdout)have some additional side effects?
Is there some more elegant way to... |
This is normal behavior in buffered I/O. Nothing strange should happen with a flush.
However, you shouldn't be messing with stdout in this case. Open your file withfopen, you'll get aFILEpointer. Use this pointer in functions likefprintfto print directly in it, and flush it if you need immediate results. Don't forget... |
Now that I am used to programming in very memory constraint conditions, one question which I dont have an answer is : Which is more memory efficient;- for(;;) or while() ? Or are they interchangeable equally? Also comment on efficiency matters if any!
|
There is no difference in memory use between the programming language constructforandwhile. A given compiler might optimize one or the other better but you should not worry about this. With memory constraint conditions the most important thing is going to be your data structures and system design. A poor system des... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:C programming : How does free know how much to free?
In C the function malloc takes an argument, specifiying how many bytes to alloacte.
How ever the function free doesn't take any arguments but a pointer.
How does free know how many bytes... |
This information such as the size of the allocation is kept within the memory allocator itself.
Internally, there's some data-structure that keeps a list of all the active memory allocations, their sizes, and their addresses. Exactly how it works is fairly complicated as there are lot of different memory allocation a... |
why it is much more difficult to provide wrappers in other languages to C++ code as opposed to C code ?
|
Every language has it's unique challenges when it comes to interacting with other languages.
You could consider C++ 'more difficult' in a sense due to its features that other languages don't have. Take for example multiple inheritance. This is a very tricky feature, and is one that many people simply say not to use a... |
I want to read all integers from a file and put them all in an array
```
./prog input.txt
```
where input.txt contains for example the following numbers
```
-6 8 9 0 45 54 67 0 12
23 3 -25 12 67 6 9 -9
```
How to do this without knowing the number of integer in advance
thanks for anyone answer !
|
Something like this. (Not tested)
```
while(!feof(inFile)){ //inFile is your pointer to the file opened with fopen()
fscanf(inFile,"%d",&a[i]); //a is your array
i++;
}
```
This way in yourivariable you will have the number of items in the file (+1) and you'll get all numbers in the array.
|
"No functions registered by atexit() in the calling process image are registered in the new process image".
Here is code:
```
pid = fork();
if (pid == 0) {
atexit(check_mem);
return execv(...);
}
```
check_mem function not getting called after execv(). Because of above "line". Any hacks to get the function ... |
atexit handlers will not execute when you exec* something.
execv replaces the current process image, including any atexit handlers you've registered, so there's really not a lot you can do - your code is gone.
|
How does this while loop works? When this *s argument terminates?
```
void putstr (char *s)
{
while (*s) putchar(*s++);
}
```
So other notable behaviors, arguments for while?
|
Logical expressions in C evaluate to false if they are 0, otherwise they evaluate to true. Thus your loop will terminate when*sis equal to 0. In the context of acharthat is when the null-terminating character is encountered.
Note that++has a higher precedence than pointer dereferencing*and so the++is bound to the poi... |
For example,if the integer is less than 255,than it can be restored in1byte,
if it's greater than 255,it requires at lest2bytes.
How to write such aBYTES_REQUIRED(i)macro?
|
If you are using a C99 compiler make the cast below to(unsigned long long).
Also you can (and should) extend the construct to 8 or 16 bytes (that's left as an exercise)
```
#include <limits.h>
#define BYTES_REQUIRED(i) \
!((unsigned long)(i) >> CHAR_BIT) ? 1 \
: !((... |
I have absolutely no idea why it returns2fora=2andb=2..
Any ideas?
```
#include <stdlib.h>
int main()
{
double a,b,c;
printf("a=");
scanf("%d", &a);
printf("b=");
scanf("%d", &b);
printf("c=");
scanf("%d", &c);
printf("x=%d", a+b);
return 0;
}
```
|
The specifier"%d"expects an integer and you are passing the address of adouble. Using the wrong specifiers inscanfleads to undefined behavior.
Also, using the wrong specifier inprintfis the same thing. Becauseprintftakes a variable number of argumentsa + bwhich is a double can't be converted to an integer.
|
I have been trying to run some sample c programs that uses the cv.h library, but what happened was that the compile complains the file could not be found. So I am guessing I need to some how set the compiler's path. How do I do that?
|
On linux, I usepkg-configto assist me on that task:
```
g++ program.cpp -o program `pkg-config --cflags --libs opencv`
```
|
I am copying N bytes frompSrctopDest. This can be done in a single loop:
```
for (int i = 0; i < N; i++)
*pDest++ = *pSrc++
```
Why is this slower thanmemcpyormemmove? What tricks do they use to speed it up?
|
Because memcpy uses word pointers instead of byte pointers, also the memcpy implementations are often written withSIMDinstructions which makes it possible to shuffle 128 bits at a time.
SIMD instructions are assembly instructions that can perform the same operation on each element in a vector up to 16 bytes long. Tha... |
How do I set the size of a file in c ? Would I do this after I fopen?
|
Yes you would do it after fopen - you can create what is know as a sparse file
```
#include <stdio.h>
int main(void) {
int X = 1024 * 1024 - 1;
FILE *fp = fopen("myfile", "w");
fseek(fp, X , SEEK_SET);
fputc('\0', fp);
fclose(fp);
}
```
That should create you a file for X Byte... |
Is there a function in C that lets you search for a particular string and delete/replace it? If not, how do I do it myself?
|
It can be dangerous to do a search and replace - unless you are just replacing single chars with another char (ie change all the 'a' to 'b'). Reason being the replaced value could try and make the char array longer. Better to copy the string and replace as you into a new char array that can hold the result. A good fin... |
Is multithreading supported in C? If yes, then how do I try? Is there any open source library that lets me do it and is the library supported on Mac OS X?
I haven't found any article saying that it's supported.
|
C is not intrinsically a multithreaded language; however there are many libraries which add threading functionality.
pthreadsis a library compatible with any POSIX system, so it is supported on OSX. I foundhttps://hpc-tutorials.llnl.gov/posix/to be a good place to start.Win32 has a threading library for C described a... |
I am pretty new to programming and I want to know how to detect a memory leak? If you are going to recommend a utility, please try to find one that works on Mac OS X Lion.
P.S. I tried valgrind, it doesn't work on 10.7/Lion.
|
Valgrind is an excellent cross platform toolhttp://valgrind.org/
And best of all its Open Source
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Function Free() in C doesn't work
I just asked a question about free(), check the link below. If I can't use if(pointer != NULL), then what can I use, just in case it doesn't work because of a stupid mistake I made.
Function free() in C i... |
Whenever you free a pointer you should set it to null - then you can use your test safetly
```
free(pointer);
pointer=NULL;
if(!pointer)
{
pointer=malloc(42);
}
```
You could even create your own free function so you dont forget to set to null.
```
void myfree(void **ptr)
{
free(*ptr);
*ptr=NULL;
}
```... |
Now that I am used to programming in very memory constraint conditions, one question which I dont have an answer is : Which is more memory efficient;- for(;;) or while() ? Or are they interchangeable equally? Also comment on efficiency matters if any!
|
There is no difference in memory use between the programming language constructforandwhile. A given compiler might optimize one or the other better but you should not worry about this. With memory constraint conditions the most important thing is going to be your data structures and system design. A poor system des... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:C programming : How does free know how much to free?
In C the function malloc takes an argument, specifiying how many bytes to alloacte.
How ever the function free doesn't take any arguments but a pointer.
How does free know how many bytes... |
This information such as the size of the allocation is kept within the memory allocator itself.
Internally, there's some data-structure that keeps a list of all the active memory allocations, their sizes, and their addresses. Exactly how it works is fairly complicated as there are lot of different memory allocation a... |
why it is much more difficult to provide wrappers in other languages to C++ code as opposed to C code ?
|
Every language has it's unique challenges when it comes to interacting with other languages.
You could consider C++ 'more difficult' in a sense due to its features that other languages don't have. Take for example multiple inheritance. This is a very tricky feature, and is one that many people simply say not to use a... |
I want to read all integers from a file and put them all in an array
```
./prog input.txt
```
where input.txt contains for example the following numbers
```
-6 8 9 0 45 54 67 0 12
23 3 -25 12 67 6 9 -9
```
How to do this without knowing the number of integer in advance
thanks for anyone answer !
|
Something like this. (Not tested)
```
while(!feof(inFile)){ //inFile is your pointer to the file opened with fopen()
fscanf(inFile,"%d",&a[i]); //a is your array
i++;
}
```
This way in yourivariable you will have the number of items in the file (+1) and you'll get all numbers in the array.
|
"No functions registered by atexit() in the calling process image are registered in the new process image".
Here is code:
```
pid = fork();
if (pid == 0) {
atexit(check_mem);
return execv(...);
}
```
check_mem function not getting called after execv(). Because of above "line". Any hacks to get the function ... |
atexit handlers will not execute when you exec* something.
execv replaces the current process image, including any atexit handlers you've registered, so there's really not a lot you can do - your code is gone.
|
How does this while loop works? When this *s argument terminates?
```
void putstr (char *s)
{
while (*s) putchar(*s++);
}
```
So other notable behaviors, arguments for while?
|
Logical expressions in C evaluate to false if they are 0, otherwise they evaluate to true. Thus your loop will terminate when*sis equal to 0. In the context of acharthat is when the null-terminating character is encountered.
Note that++has a higher precedence than pointer dereferencing*and so the++is bound to the poi... |
For example,if the integer is less than 255,than it can be restored in1byte,
if it's greater than 255,it requires at lest2bytes.
How to write such aBYTES_REQUIRED(i)macro?
|
If you are using a C99 compiler make the cast below to(unsigned long long).
Also you can (and should) extend the construct to 8 or 16 bytes (that's left as an exercise)
```
#include <limits.h>
#define BYTES_REQUIRED(i) \
!((unsigned long)(i) >> CHAR_BIT) ? 1 \
: !((... |
I have absolutely no idea why it returns2fora=2andb=2..
Any ideas?
```
#include <stdlib.h>
int main()
{
double a,b,c;
printf("a=");
scanf("%d", &a);
printf("b=");
scanf("%d", &b);
printf("c=");
scanf("%d", &c);
printf("x=%d", a+b);
return 0;
}
```
|
The specifier"%d"expects an integer and you are passing the address of adouble. Using the wrong specifiers inscanfleads to undefined behavior.
Also, using the wrong specifier inprintfis the same thing. Becauseprintftakes a variable number of argumentsa + bwhich is a double can't be converted to an integer.
|
I have been trying to run some sample c programs that uses the cv.h library, but what happened was that the compile complains the file could not be found. So I am guessing I need to some how set the compiler's path. How do I do that?
|
On linux, I usepkg-configto assist me on that task:
```
g++ program.cpp -o program `pkg-config --cflags --libs opencv`
```
|
I am copying N bytes frompSrctopDest. This can be done in a single loop:
```
for (int i = 0; i < N; i++)
*pDest++ = *pSrc++
```
Why is this slower thanmemcpyormemmove? What tricks do they use to speed it up?
|
Because memcpy uses word pointers instead of byte pointers, also the memcpy implementations are often written withSIMDinstructions which makes it possible to shuffle 128 bits at a time.
SIMD instructions are assembly instructions that can perform the same operation on each element in a vector up to 16 bytes long. Tha... |
How do I set the size of a file in c ? Would I do this after I fopen?
|
Yes you would do it after fopen - you can create what is know as a sparse file
```
#include <stdio.h>
int main(void) {
int X = 1024 * 1024 - 1;
FILE *fp = fopen("myfile", "w");
fseek(fp, X , SEEK_SET);
fputc('\0', fp);
fclose(fp);
}
```
That should create you a file for X Byte... |
Is there a function in C that lets you search for a particular string and delete/replace it? If not, how do I do it myself?
|
It can be dangerous to do a search and replace - unless you are just replacing single chars with another char (ie change all the 'a' to 'b'). Reason being the replaced value could try and make the char array longer. Better to copy the string and replace as you into a new char array that can hold the result. A good fin... |
Is multithreading supported in C? If yes, then how do I try? Is there any open source library that lets me do it and is the library supported on Mac OS X?
I haven't found any article saying that it's supported.
|
C is not intrinsically a multithreaded language; however there are many libraries which add threading functionality.
pthreadsis a library compatible with any POSIX system, so it is supported on OSX. I foundhttps://hpc-tutorials.llnl.gov/posix/to be a good place to start.Win32 has a threading library for C described a... |
I am pretty new to programming and I want to know how to detect a memory leak? If you are going to recommend a utility, please try to find one that works on Mac OS X Lion.
P.S. I tried valgrind, it doesn't work on 10.7/Lion.
|
Valgrind is an excellent cross platform toolhttp://valgrind.org/
And best of all its Open Source
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Function Free() in C doesn't work
I just asked a question about free(), check the link below. If I can't use if(pointer != NULL), then what can I use, just in case it doesn't work because of a stupid mistake I made.
Function free() in C i... |
Whenever you free a pointer you should set it to null - then you can use your test safetly
```
free(pointer);
pointer=NULL;
if(!pointer)
{
pointer=malloc(42);
}
```
You could even create your own free function so you dont forget to set to null.
```
void myfree(void **ptr)
{
free(*ptr);
*ptr=NULL;
}
```... |
I'm trying to make my program output a sentence but only if it will start at the beginning of the line. For example, if this is my current console window:
Hello World! [Do not print if text is going to start here][Print if text is going to start here]
Is there a way to check if the current output line is empty? Or e... |
C isn't going to track the state of the standard output. You'll have to do it yourself. At every point where you generate output, set a flag that indicates if you ended the line or not.
|
I'm creating an Alt-Tab pedal with an Arduino. The idea is that the user will just press down on a pedal that will hit a button on the Arduino, and this would be the equivalent of hitting theALT+TABkey (thereby allowing you to stealthily switch windows).
I'm also open to just minimizing the window.
The problem is, I... |
```
SendKeys.Send("%{TAB}");
```
Or use SendInput() in a C program.
|
I'm looking for a good non-blocking sleep timer in C for windows.
Currently I am usingsleep(10);which of course is a blocking timer.
Also I want it to consume no system resources, like my sleep timer it doesn't use any CPU or system resources which I am happy with.
So, what is the best non-blocking sleep timer I co... |
You dont need an API you need to change your design.
A simple one is this.
You can have multiple threads, One is the Manager Thread and other are Worker Threads.
At every 10 seconds the manager thread will wake up create a new worker thread and go to sleep.
The worker threads will keep working even when the Manage... |
```
-(IBAction)enterVeryBasics:(id)sender {
VeryBasics *enterIntro = [[VeryBasics alloc]initWithNibName:Nil bundle:Nil];
[self presentModalViewController:enterIntro animated:YES];
[enterIntro release];
}
```
I have this code here, and on[self presentModalViewController:enterIntro animated:YES];it's giving me a ... |
Look at UIViewController Class reference instance method signature:
```
- (void)presentModalViewController:(UIViewController *)modalViewController animated:(BOOL)animated
```
Is your VeryBasics is Subclass of UIViewController ? It doesn't look like from your code.
|
I am working with hex values. Until now I know how to print hex values and also precision thing. Now I want to compare the hex values. For example I am reading data from a file into a char buffer. Now I want to compare the hex value of data in the buffer. Is there anything like this?
```
if hex(buffer[i]) > 0X3F
t... |
You're nearly there:
```
if (buffer[i] > 0x3f)
{
// do something
}
```
Note that there is no need to "convert" anything to hex - you can just compare character or integer values directly, since a hex constant such as 0x3f is just another way of representing an integer value. 0x3f == 63 (decimal) == ASCII '?'.
|
I am trying to return a pointer from a function. But I am getting a segmentation fault. Someone please tell what is wrong with the code
```
#include <stdio.h>
int *fun();
main()
{
int *ptr;
ptr = fun();
printf("%d", *ptr);
}
int *fun()
{
int *point;
*point = 12;
return point;
}
```
|
Allocate memory before using the pointer. If you don't allocate memory*point = 12is undefined behavior.
```
int *fun()
{
int *point = malloc(sizeof *point); /* Mandatory. */
*point=12;
return point;
}
```
Also yourprintfis wrong. You need to dereference (*) the pointer.
```
printf("%d", *ptr);
... |
I am not able to understand why
```
float x = (4+2%-8);
printf("%f\n", x);
```
prints 6.000000 and
```
printf("%f\n", (4+2%-8));
```
prints 0.000000. Any information will be helpful.
Regards.
|
The expression(4 + 2 % -8)produces an integer and you are trying to print a float (and they don't match).
In the first case the integer is converted tofloat(because of the assignment) so later on theprintfworks because the value is in a format%fexpects.
Try this:
```
printf("%f\n", (4.0 + 2 % -8));
... |
Well, I want to pass a string value from one file to another, how do I do that ? I don't want to save it to a text file and read it in the other one, I directly want to pass it to another c file .Thanks in advance.
|
maybe just a #define MY_STR "your value" will do the job.
just create a .h file and include in both your C files
```
#ifndef _MY_HEADER_H
#define _MY_HEADER_H
#define MY_STR "your value"
#endif
```
then in your sources
```
#include "yourfile.h"
```
and use your MY_STR as a constant (please note that MY_STR will... |
I want to create a string based on the value passed as argument to the MACRO FUNCTION.
Something Like:
```
#define ABC(x,y) return "anystr_x_y.tar.bz2"
main()
{
a = ABC(2,3);
}
```
So Finally, It should return "anystr_2_3.tar.bz2"
I was wondering how to create that string with the value passed as argument to MAC... |
Define your macro like this, using the "stringize operator":
```
#define ABC(x,y) "anystr_" #x "_" #y ".tar.bz2"
```
|
I'm writing a simple library for checking the internet access status of network interfaces by C on Linux.
Checking the status for all network interfaces (configured or not configured)
Would you please give me where i can refer ( such as documents, example code ...) or any hints?
|
The simplest method is probably to check for the existence of a default route through that interface. You could call out to/bin/ip routeto do this.
|
Can someone please shed some light about this particular for loop in matlab C ? Initial is equal to each other !
```
for(ir = ir; ir<=temp; ir++){
}
```
Thanks in advance.
|
Ifiris an integer, then the loop essentially doesir = max(ir, ceil(temp))
|
I need to generate a mask vector (unsigned char type) which contains 2 of '1's only, i.e. 0x03, 0x50 and etc.
I also need these two '1's distributed randomly in the vector.
How can I do this in c/c++?
Thank you!
Edit:
A more challenging and general case is asked here.How to generate n random 1s in an unsigned char... |
I would do like this:
```
srand(time(0));
int s[8];
for (int i=0; i<8; i++) s[i] = i;
// s[0], s[1] are two random locations for '1's
u = rand()%8;
swap(s[0], s[u]);
v = rand()%7+1;
swap(s[1], s[v]);
unsigned char c = (1 << s[0]) | (1 << s[1]);
```
|
Is it possible to pass the data from CPU to GPU without explicitly passing it as a parameter?
I don't want to pass it as a parameter primarily for syntax sugar reasons - I have about 20 constant parameters I need to pass, and also because I successively invoke two kernels with (almost) same parameters.
I want someth... |
cudaMemcpyToSymbolseems to be the function you're looking for. It works similarly tocudaMemcpy, but with an additional 'offset' argument which looks like it'll make it easier to copy across 2D arrays.
(I'm hesitant to provide code, since I'm unable to test it - but seethis threadandthis postfor reference.)
|
im stucking with Writing to Text File in the Resource, i can read from
the specified file, but cant write, its says Stream is not writeable.
there is any way to fix it ? i do it for my program builder, thanks in advice!
|
You can not write the the application bundle, pick another location, perhaps the Documents directory on iOS or the Application Support directory in OSX.
On iOS the resource bundle is also signed, another reason writing to it is not allowed.
|
On these screenshots we can see unordinary window frame in different applications:
QIP logo on its login window frame (not client area) -http://postimage.org/image/2fdjg0h44/Buttons (back/next) and address field on the Windows 7 explorer window frame -http://postimage.org/image/2fdrpp7l0/In Google Chrome tabs take pl... |
That effect is accomplished using the DwmExtendFrameIntoClientArea function.
|
Firstly, what is DSUSP?
I'm trying to disable it using the following code line:
```
tntty.c_cc[VDSUSP] = _POSIX_VDISABLE;
```
But I get the error that "VDSUSP is undeclared"
|
The Linuxtermios(3)man page describes it thus (emphasis mine):
VDSUSP(not in POSIX;not supported under Linux; 031, EM,
Ctrl-Y) Delayed suspend character: send SIGTSTP signal when the
character is read by the user program. Recognized when IEXTEN
and ISIG are set, and the system supports job control, and t... |
I am looking at some code from one of our customers and found this function parameter I've never seen before:
```
some_function('ESFc');
```
In the debugger I set the value to
```
char c = 'ESFc';
```
and it equals 99
He also is using 'ESSc', 'ESCm' and 'ESBd' which eval to 99, 109 and 100
What is this? Is it so... |
It's a multi-character literal, but its value is not 99. The type of'ESFc'is actually anint, and when you store it in acharit loses precision. See this question:
What do single quotes do in C++ when used on multiple characters?
|
What causes the output "Hello" when I enable -O for gcc ? Shouldn't it still segfault (according to thiswiki) ?
```
% cat segv.c
#include <stdio.h>
int main()
{
char * s = "Hello";
s[0] = 'Y';
puts(s);
return 0;
}
% gcc segv.c && ./a.out
zsh: segmentation fault ./a.out
% gcc -O segv.c && ./a.out
H... |
It'sundefined behavior(might crash,might not do anything, etc) to change string literals. Well explained in aC FAQ.
6.4.5/6It is unspecified whether these arrays are distinct provided their
elements have the appropriate values. If the program attempts to
modify such an array,the behavior is undefined.
|
why doesn't the following line of code work?
typedef float[MAT_ROW_SIZE][MAT_COL_SIZE] mat;
what should I do?
(I wanna avoid defining a struct)
|
The identifier (the name) must come first. Try
```
typedef float mat[MAT_ROW_SIZE][MAT_COL_SIZE];
```
|
In my clutter program written in c I have two Textures that overlap. One of them stays the same while the program is running and the other moves in to overlap from somewhere else on the stage. Because the second texture was created after the first one, it covers part of it up, but I want the first Texture to stay on t... |
you can useclutter_actor_raise()andclutter_actor_lower():
http://developer.gnome.org/clutter/stable/ClutterActor.html#clutter-actor-raise
if the actors belong to the same container.
|
InC996.7.1 it says
At most, one storage-class specifier may be given in the declaration
specifiers in a declaration
I knowexternandstaticare both storage class specifiers butexternbasically states to the compiler that the variable is declared elsewhere and worry about it later.externandstaticto me areNOTmutually e... |
Well,staticmeansInternal Linkage,externmeansExternal Linkage.
Internal Linkagerefers to everything only in scope of a Translation unit.
External Linkagerefers to things that exist beyond a particular translation unit. In other words, accessable through the whole program.
So both are mutually exclusive.
|
How can I accept a command line argument this way:
```
./a.out --printall
```
so that inside my program, I have something like
```
if (printall) {
// do something
}
```
I don't want to do this:
```
if (argc == 2)
//PRINTALL exists
```
since my program can have multiple command line options:
```
./a.out --pr... |
(About the argument parsing part of the question:)
You will needgetopt_long()from<unistd.h>. This is a GNU extension.
For greater portability, you might consider Boostprogram options, though that's a compiled library.
|
I was recently asked in an interview how to set the 513th bit of achar[1024]in C, but I'm unsure how to approach the problem. I sawHow do you set, clear, and toggle a single bit?, but how do I choose the bit from such a large array?
|
```
int bitToSet = 513;
inArray[bitToSet / 8] |= (1 << (bitToSet % 8));
```
...making certain assumptions about character size and desired endianness.
EDIT: Okay, fine. You can replace8withCHAR_BITif you want.
|
I am trying to return a pointer from a function. But I am getting a segmentation fault. Someone please tell what is wrong with the code
```
#include <stdio.h>
int *fun();
main()
{
int *ptr;
ptr = fun();
printf("%d", *ptr);
}
int *fun()
{
int *point;
*point = 12;
return point;
}
```
|
Allocate memory before using the pointer. If you don't allocate memory*point = 12is undefined behavior.
```
int *fun()
{
int *point = malloc(sizeof *point); /* Mandatory. */
*point=12;
return point;
}
```
Also yourprintfis wrong. You need to dereference (*) the pointer.
```
printf("%d", *ptr);
... |
I am not able to understand why
```
float x = (4+2%-8);
printf("%f\n", x);
```
prints 6.000000 and
```
printf("%f\n", (4+2%-8));
```
prints 0.000000. Any information will be helpful.
Regards.
|
The expression(4 + 2 % -8)produces an integer and you are trying to print a float (and they don't match).
In the first case the integer is converted tofloat(because of the assignment) so later on theprintfworks because the value is in a format%fexpects.
Try this:
```
printf("%f\n", (4.0 + 2 % -8));
... |
Well, I want to pass a string value from one file to another, how do I do that ? I don't want to save it to a text file and read it in the other one, I directly want to pass it to another c file .Thanks in advance.
|
maybe just a #define MY_STR "your value" will do the job.
just create a .h file and include in both your C files
```
#ifndef _MY_HEADER_H
#define _MY_HEADER_H
#define MY_STR "your value"
#endif
```
then in your sources
```
#include "yourfile.h"
```
and use your MY_STR as a constant (please note that MY_STR will... |
I want to create a string based on the value passed as argument to the MACRO FUNCTION.
Something Like:
```
#define ABC(x,y) return "anystr_x_y.tar.bz2"
main()
{
a = ABC(2,3);
}
```
So Finally, It should return "anystr_2_3.tar.bz2"
I was wondering how to create that string with the value passed as argument to MAC... |
Define your macro like this, using the "stringize operator":
```
#define ABC(x,y) "anystr_" #x "_" #y ".tar.bz2"
```
|
I'm writing a simple library for checking the internet access status of network interfaces by C on Linux.
Checking the status for all network interfaces (configured or not configured)
Would you please give me where i can refer ( such as documents, example code ...) or any hints?
|
The simplest method is probably to check for the existence of a default route through that interface. You could call out to/bin/ip routeto do this.
|
Can someone please shed some light about this particular for loop in matlab C ? Initial is equal to each other !
```
for(ir = ir; ir<=temp; ir++){
}
```
Thanks in advance.
|
Ifiris an integer, then the loop essentially doesir = max(ir, ceil(temp))
|
I need to generate a mask vector (unsigned char type) which contains 2 of '1's only, i.e. 0x03, 0x50 and etc.
I also need these two '1's distributed randomly in the vector.
How can I do this in c/c++?
Thank you!
Edit:
A more challenging and general case is asked here.How to generate n random 1s in an unsigned char... |
I would do like this:
```
srand(time(0));
int s[8];
for (int i=0; i<8; i++) s[i] = i;
// s[0], s[1] are two random locations for '1's
u = rand()%8;
swap(s[0], s[u]);
v = rand()%7+1;
swap(s[1], s[v]);
unsigned char c = (1 << s[0]) | (1 << s[1]);
```
|
Is it possible to pass the data from CPU to GPU without explicitly passing it as a parameter?
I don't want to pass it as a parameter primarily for syntax sugar reasons - I have about 20 constant parameters I need to pass, and also because I successively invoke two kernels with (almost) same parameters.
I want someth... |
cudaMemcpyToSymbolseems to be the function you're looking for. It works similarly tocudaMemcpy, but with an additional 'offset' argument which looks like it'll make it easier to copy across 2D arrays.
(I'm hesitant to provide code, since I'm unable to test it - but seethis threadandthis postfor reference.)
|
im stucking with Writing to Text File in the Resource, i can read from
the specified file, but cant write, its says Stream is not writeable.
there is any way to fix it ? i do it for my program builder, thanks in advice!
|
You can not write the the application bundle, pick another location, perhaps the Documents directory on iOS or the Application Support directory in OSX.
On iOS the resource bundle is also signed, another reason writing to it is not allowed.
|
On these screenshots we can see unordinary window frame in different applications:
QIP logo on its login window frame (not client area) -http://postimage.org/image/2fdjg0h44/Buttons (back/next) and address field on the Windows 7 explorer window frame -http://postimage.org/image/2fdrpp7l0/In Google Chrome tabs take pl... |
That effect is accomplished using the DwmExtendFrameIntoClientArea function.
|
Is it possible to convert a hexadecimal value to its respective ASCII character, not using theString.fromCharCodemethod, in JavaScript?
For example:
JavaScript:
```
0x61 // 97
String.fromCharCode(0x61) // a
```
C-like:
```
(char)0x61 // a
```
|
You can use the\xNNnotation:
```
var str = "\x61";
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.