question
stringlengths
25
894
answer
stringlengths
4
863
In the execve() man page it is said that argv is a list of string arguments which is ended by a null pointer. But what is the NP for? I mean, the number of arguments is stored in argc, so what's the point of the null pointer?
execvedoes not takeargcas a parameter, it manually counts the arguments you give asargvto determineargcitself. This is for compatibility withexeclwhich takes a variable number of arguments instead of anargvarray.
I get a segmentation fault afterfreeing a certain pointer: ``` free(studentDB->name); ``` I can get its value without any errors or warnings: ``` printf("[DBG] studentDB->name: %s\n", studentDB->name); ``` However, as I said, the program crashes when I try to free it. What are the most common causes for afreecommand leading to a segmentation fault?
If you didn'tmalloc()it, you can'tfree()it. Where doesstudentDB->namecome from?
Is there any way to decompile Linux .so?
There aredecompilers, but a decompiler might not emit code in the same language that the original program was written in. There are alsodisassemblers, which will reassemble the machine code into assembly. The Decompilation Wikimay be a good source of additional information.
I already know that I can trace memory leaks in my code withmtraceandvalgrindon Linux, both of which are unavailable for Windows. Which Windows program would you recommend to trace memory leaks? I'm an Eclipse user and I've been working with C for a month or two now, so I prefer a user-friendly solution over something more advanced.
Application Verifier will do this quite well,http://msdn.microsoft.com/en-us/library/ms220948.aspx
Here is the situation : Some process writes lines into a fifo file (created withmkfifo). At some point in my program, I want to read the last line in the fifo, and discard all the others. The procedure may block, only if there is less than one line in the fifo. I can't come up with a clean way to do this, any ideas ? EDIT : The writing process will never stop writing lines into the fifo, What I mean by the last line is the last by the time I read the fifo. It is not necessarily followed by a EOF.
If your main concern is that the read will block then open the FIFO as non-blocking. I assume you know what you are looking for in the stream and will simply discard everything before. You can also use something likeselect()to be informed when there is something to read off the pipe.
I'm trying to free up the memory I've allocated withmalloc, but thefreecommand doesn't seem to do its job properly according to Eclipse's debugger. How's this possible? Below is a screenshot of my debugger after it supposedly freed upseCurrent->student->year, which is clearly not the case.yearwas allocated usingmalloc. alt text http://img693.imageshack.us/img693/7840/codeo.png
free() does not normally change any values in your program - it just makes adjustments to the C runtime heap. This means that the values in the memory that was just freed are retained. However, attempts to access them from your code lead to undefined behaviour.
My friend said he thinks i may have made a mistake in my programme and wanted to see if i really did. He asked me to send him the binary opposed to the source. As i am new to this i am paranoid that he is doing someting to it? What can you do with the binary that would mean you wouldnt want the source? thank
Black-box testing. Having the source may skew your view on how the program may be behaving.
The question is simple "Say we have an integer1 <= n <= 12,How to usestrftimeto displayJanuaryfor '1',Februaryfor '2',Marchfor '3' and so on ... ?"
``` #include <stdio.h> #include <time.h> size_t monthName( char* buf, size_t size, int month) { struct tm t = {0}; t.tm_mon = month - 1; // turn month 1..12 to 0..11 as `struct tm` wants return strftime( buf, size, "%B", &t); } int main(int argc, char* argv[]) { char buf[10]; monthName( buf, sizeof( buf), 9); printf( "%s\n", buf); return 0; } ```
I am reading a book on game AI. One of the terms that is being used is to normalize a vector which is to turn a vector into a unit. To do so you must divide each dimensionx,yandzby its magnitude. We must turn vector into a unit before we do anything with it. Why? And could anyone give some scenarios where we must use a unit vector? Thanks!
You don't have to normalize vectors, but it makes a lot of equations a little simpler when you do. It could also make API's smaller: any form of standardization has the potential to reduce the number of functions necessary. Here's a simple example. Suppose you want to find the angle between two vectors u and v. If they are unit vectors, the angle is just arccos(uv). If they're not unit vectors, the angle is arccos(uv/(|u| |v|)). In that case, you end up computing the norms of u and v anyway.
I heard fopen supports UTF8 but i dont know how to convert an array of shorts to utf8 How do i create a file with unicode letters in it? I prefer to use only built in libraries (no boost which is not installed on the linux box). I do need to use fopen but its pretty simple to.
fopen(3)supports any valid byte sequence; the encoding is unimportant. Usenl_langinfo(3)withCODESETto get what charset you should use for the encoding, and libiconv or icu for the actual encoding.
Is there a way to do check for numerical equality in macros? I want to do something like ``` #define choice 3 #if choice == 3 .... #endif #if choice == 4 ... #endif ``` Does C macros have support for things like this?
Another way to write your code uses chained#elifdirectives: ``` #if choice == 3 ... #elif choice == 4 ... #else #error Unsupported choice setting #endif ``` Note that ifchoiceis not#defined, the compiler (preprocessor) treats it as having the value0.
If I declare a pointer to a struct in .h for example: ``` my_struct_t *ptr; ``` ... and then I checkif(ptr==NULL)in the code, without actually setting ptr to NULL or allocating memory for it, can I do that check to see if its equal to NULL? essentially what I'm asking is, by having ptr in the .h, does it get set to NULL automatically, or do I have to do that? Thanks, Hristo revisiont: this is done in C
From K&R2nd: In the absense of explicit initializations, external and static variables are guaranteed to be initialized to zero. So, yes. That appears to be in section A8.7 of the 1990 standard. Don't know where to look in the 1999 standard.
If Python was so fast as C, the latter would be present in python apps/libraries? Example: if Python was fast as C would PIL be written completely in Python?
To access "legacy" C libraries and OS facilities.
For a project at university I need to extend an existing C application, which shall in the end run on a wide variety of commercial and non-commercial unix systems (FreeBSD, Solaris, AIX, etc.). Which things do I have to consider when I want to write a C program which is most portable?
The best advice I can give, is to move to a different platform every day, testing as you go.This will make the platform differences stick out like a sore thumb, and teach you the portability issues at the same time. Saving the cross platform testing for the end, will lead to failure. That aside Integer sizes can vary.floating point numbers might be represented differently.integers can have different endianism.Compilation options can vary.include file names can vary.bit field implementations will vary. It is generally a good idea to set your compiler warning level up as high as possible, to see the sorts of things the compiler can complain about.
Nearly every (relatively) new book about c programming I've seen doesn't seem to adhere to the C99 standard, or they cover it in an extra chapter. Comming from a Java background, the C99 standard made the migration (well, still migrating ^^) much easier for me, and this probably applies to other languages, too. It seems like C99 hasn't reached most of the C developers yet. But why?
Short answer:compiler support is slow to get installed and c programmers are a conservative lot who change their behavior slowly.
just a sanity check please: in VB.NET: dim myarray(5) as integer gives six elements 0 to 5 but in c? int myarray[5]; gives five elements 0 to 4 ? is this correct?
Yes that's correct! Hope I saved your sanity.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed8 months ago.Improve this question I've just started learning C and I have a hard time finding bugs, memory leaks and the like. Which are good tools to assist you in finding such things? I heard of Valgrind but are there others?
For me (on Linux) there are: GDBused to find bugsValgrindfind memory leaks
I'm working on a Command Line app to help me on launchd tasks to know if a task is running by returning a BOOL, the problem comes when i need to do a command line and obtain the output for further parsing. i'm coding it in C/C++ so i can't use NSTask for it, any ideas on how to achieve the goal? The Command ``` sudo launchctl list -x [job_label] ``` If i use system(), i'm unable to get the output so in further research I came with popen(), but no success there. Thanks in advance.
You'll want to create a pipe from which you can read the output of the program. This will involve usingpipe,fork,exec*, and maybe evendup. There's a good tutorial onthe linux documentation project.
I've been trying to determine whether the 3GB switch is on or off on the system my program is running by calling GetSystemInfo() and checking lpMaximumApplicationAddress on the SYSTEM_INFO struct. No luck. I think I am doing something wrong. How do you check whether the 3GB switch is on or not on Windows in C? Code is appreciated. thanks
Assuming your program is compiled as large address aware, you could simply callGlobalMemoryStatusExand check theullTotalVirtualfield. If it's larger than 2GB, and you're running on a 32-bit system, then the 3GB flag must be turned on. I actually have no idea how to 'properly' tell if Windows is natively 32 or 64 bit, but if you have a 32-bit process you could callIsWow64Processto see if you're running on a 64-bit OS. This all seems a bit indirect, I know :)
When allocating Strings on the heap (with 'malloc'),and initializing them with the standard input (using 'fgets),an unnecessary newline appears between them when trying to print them (with 'printf' and %s formatting).for example: ``` main() { char *heap1; char *heap2; heap1=malloc(10); heap2=malloc(10); fgets(heap1,10,stdin); fgets(heap2,10,stdin); printf("%s%s",heap1,heap2); } ``` with input "hi1\nhi2" produces "hi1\nhi2". compiled using gcc 4.3.4 for Debian.
fgets also reads the '\n' (newline) character. You should remove it if you don't want it to print like that. ``` heap1[strlen(heap1) - 1] = '\0'; ``` after you read the contents of heap1.
I have a C function defined as follows: ``` int s3vold_(void) {...} ``` To create a Java methods with the same argument type as the native function does the void parameter map to Pointer or nothing? E.g., ``` int s3vold(Pointer p) {...} ``` or ``` int s3vold() {...} ``` TheJNA docsonly refer to void*
Thevoidparameter maps to nothing. Thevoidparameter in C is equivalent to an empty parameter list: in other languages we leave this blank, but in C we writevoidto distinguish from a classic K&R function declaration.
In either java or c I can write a function like ``` fun(){ fun(); } ``` (ignoring syntax details) In java I get OutOfMemory exception but in C (and maybe some other languages) it seems to run forever, as if it were an infinite loop. Why don't I get OutOfMemory error here as well?
Since your function is an example oftail recursion, then most likely, the C compiler is optimizing the recursion to iteration, causing it to loop infinitely without crashing.
GCC has the ability to make a symbol link weakly via__attribute__((weak)). I want to use the a weak symbol in a static library that users can override in their application. A GCC style weak symbol would let me do that, but I don't know if it can be done with visual studio. Does Visual Studio offer a similar feature?
You can do it, here is an example in C: ``` /* * pWeakValue MUST be an extern const variable, which will be aliased to * pDefaultWeakValue if no real user definition is present, thanks to the * alternatename directive. */ extern const char * pWeakValue; extern const char * pDefaultWeakValue = NULL; #pragma comment(linker, "/alternatename:_pWeakValue=_pDefaultWeakValue") ```
Which preprocessor define should be used to specify debug sections of code? Use#ifdef _DEBUGor#ifndef NDEBUGor is there a better way to do it, e.g.#define MY_DEBUG? I think_DEBUGis Visual Studio specific, is NDEBUG standard?
Visual Studio defines_DEBUGwhen you specify the/MTdor/MDdoption,NDEBUGdisables standard-C assertions. Use them when appropriate, ie_DEBUGif you want your debugging code to be consistent with theMS CRT debugging techniquesandNDEBUGif you want to be consistent withassert(). If you define your own debugging macros (and you don't hack the compiler or C runtime), avoid starting names with an underscore, as these are reserved.
I'm trying to programmatically send modified keystrokes, for instance a capital "A". The problem is that the shift modifier does not seem to have any effect. In my code, I have two events, one for the shift key down, and another for the 'm' key down. ``` CGEventRef mDown = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)46, true); CGEventRef shiftDown = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)56, true); CGEventPost(kCGAnnotatedSessionEventTap, shiftDown); CGEventPost(kCGAnnotatedSessionEventTap, mDown);} CFRelease(shiftDown); CFRelease(mDown); ``` The result is unfortunately always a small case 'm'! Any help would be appreciated.
You should be using CGEventKeyboardSetUnicodeString instead. Seeherefor some sample code.
I need to execute a unix command with different args in a loop. Now I wonder if I should use execvp(), passing in the cmd and the args, or use system, building a string consisting of cmd + args?
Well, the other answers aremostlycorrect. System, while not onlyforks and thenexecs, it doesn'texecyour process, it runs the default shell, passing your program as an argument. So, unless you really want a shell (for parameter parsing and the like) it ismuchmore efficient to do something like: ``` int i = fork(); if ( i != 0 ) { exec*(...); // whichever flavor fits the bill } else { wait(); // or something more sophisticated } ```
I have a listcontrol with three columns. I want to read what text is in the third column. I need this, because i want color this column according to that what text is in it. Can anyone tell me, how to read the data? Thanks in advance! kampi
If your control's associated CListCtrl is called m_listCtrl simply use: ``` CString colText = m_listCtrl.GetItemText(item, subitem); ``` You associate that variable with the control itself via something like this: ``` void CMyDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_LIST1, m_listCtrl); } ```
My function takes pointer*das parameter. I wrote that line -EXEC SQL VAR d->x is STRING;Actually I want a variable which can store the value ofd->x. with that variable i can manipulate some other work. I get the following error ``` Semantic error EXEC SQL VAR d->x is STRING; ``` Waiting for your suggestions.
If I were to guess, you want to have achararray, or acharpointer with enough memory, and then put your query string in it: ``` char query[BIG_ENOUGH]; sprintf(query, "EXEC SQL VAR %s is STRING;", d->x); ``` The above assumes that your have a string ind->x, and that you want the string value in your SQL query. I don't know if your SQL query is well-formed though. If this is not what you want, you need to post more information.
In a C program I get "passing argument ... from incompatible pointer type" warnings, however I want to get error and terminate compilation instead of warning. What flag shall I set in makefile?
If using gcc, I think the option combination you need is-fstrict-aliasing -Wstrict-aliasing=3 -Werror=strict-aliasing. Seethis textfor documentation of thestrict-aliasingoption.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed13 years ago. In recursive function, the variable should be declared as local or static or global variable? Thanks in advance...
It depends. A static variable means you have one variable that's shared across all recursive invocations. A normal local variable means each recursive invocation gets its own copy of that variable. You need to choose the one that makes sense for what you're doing. A global is like a static local variable (one variable shared by all invocations) but it's also visible to the rest of the application.
I am new to C and I am trying to figure out what the printf method does. I have this little bit of code and I keep getting errors when I use the %x for exampleprintf(“a) %x\n”, px);x% is for hex, Am i just using the wrong type here or is something else going on? what should the code I have below be printing out? ``` int x = 10; int y = 20; int *px = &x; int *py = &y; printf(“a) %x\n”, px); printf(“b) %x\n”, py); px = py; printf(“c) %d\n”, *px); printf(“d) %x\n”, &px); x = 3; y = 5; printf(“e) %d\n”, *px); printf(“f) %d\n”, *py); ```
Using integer formats (%x,%d, or the like) for printing pointers is not portable. So, for any of the pointer ones (px,py, and&px, but not*pxand*py), you should be using%pas your format instead.
I am new to C++ and I am trying to understand some code. What does it mean to have a * in front of the datatype ? and why is the class Name in front of the method nameCAStar::LinkChild ``` void CAStar::LinkChild(_asNode *node, _asNode *temp) { } ```
A * in front of the data type says that the variable is a pointer to the data type, in this case, a pointer to a node. Instead of passing a copy of the entire "node" into the method, a memory address, or pointer, is passed in instead. For details, seePointers in this C++ Tutorial.The class name in front of the method name specifies that this is defining a method of theCAStarclass. For details, see theTutorial pages for Classes.
just a sanity check please: in VB.NET: dim myarray(5) as integer gives six elements 0 to 5 but in c? int myarray[5]; gives five elements 0 to 4 ? is this correct?
Yes that's correct! Hope I saved your sanity.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed8 months ago.Improve this question I've just started learning C and I have a hard time finding bugs, memory leaks and the like. Which are good tools to assist you in finding such things? I heard of Valgrind but are there others?
For me (on Linux) there are: GDBused to find bugsValgrindfind memory leaks
I'm working on a Command Line app to help me on launchd tasks to know if a task is running by returning a BOOL, the problem comes when i need to do a command line and obtain the output for further parsing. i'm coding it in C/C++ so i can't use NSTask for it, any ideas on how to achieve the goal? The Command ``` sudo launchctl list -x [job_label] ``` If i use system(), i'm unable to get the output so in further research I came with popen(), but no success there. Thanks in advance.
You'll want to create a pipe from which you can read the output of the program. This will involve usingpipe,fork,exec*, and maybe evendup. There's a good tutorial onthe linux documentation project.
I've been trying to determine whether the 3GB switch is on or off on the system my program is running by calling GetSystemInfo() and checking lpMaximumApplicationAddress on the SYSTEM_INFO struct. No luck. I think I am doing something wrong. How do you check whether the 3GB switch is on or not on Windows in C? Code is appreciated. thanks
Assuming your program is compiled as large address aware, you could simply callGlobalMemoryStatusExand check theullTotalVirtualfield. If it's larger than 2GB, and you're running on a 32-bit system, then the 3GB flag must be turned on. I actually have no idea how to 'properly' tell if Windows is natively 32 or 64 bit, but if you have a 32-bit process you could callIsWow64Processto see if you're running on a 64-bit OS. This all seems a bit indirect, I know :)
When allocating Strings on the heap (with 'malloc'),and initializing them with the standard input (using 'fgets),an unnecessary newline appears between them when trying to print them (with 'printf' and %s formatting).for example: ``` main() { char *heap1; char *heap2; heap1=malloc(10); heap2=malloc(10); fgets(heap1,10,stdin); fgets(heap2,10,stdin); printf("%s%s",heap1,heap2); } ``` with input "hi1\nhi2" produces "hi1\nhi2". compiled using gcc 4.3.4 for Debian.
fgets also reads the '\n' (newline) character. You should remove it if you don't want it to print like that. ``` heap1[strlen(heap1) - 1] = '\0'; ``` after you read the contents of heap1.
I have a C function defined as follows: ``` int s3vold_(void) {...} ``` To create a Java methods with the same argument type as the native function does the void parameter map to Pointer or nothing? E.g., ``` int s3vold(Pointer p) {...} ``` or ``` int s3vold() {...} ``` TheJNA docsonly refer to void*
Thevoidparameter maps to nothing. Thevoidparameter in C is equivalent to an empty parameter list: in other languages we leave this blank, but in C we writevoidto distinguish from a classic K&R function declaration.
In either java or c I can write a function like ``` fun(){ fun(); } ``` (ignoring syntax details) In java I get OutOfMemory exception but in C (and maybe some other languages) it seems to run forever, as if it were an infinite loop. Why don't I get OutOfMemory error here as well?
Since your function is an example oftail recursion, then most likely, the C compiler is optimizing the recursion to iteration, causing it to loop infinitely without crashing.
GCC has the ability to make a symbol link weakly via__attribute__((weak)). I want to use the a weak symbol in a static library that users can override in their application. A GCC style weak symbol would let me do that, but I don't know if it can be done with visual studio. Does Visual Studio offer a similar feature?
You can do it, here is an example in C: ``` /* * pWeakValue MUST be an extern const variable, which will be aliased to * pDefaultWeakValue if no real user definition is present, thanks to the * alternatename directive. */ extern const char * pWeakValue; extern const char * pDefaultWeakValue = NULL; #pragma comment(linker, "/alternatename:_pWeakValue=_pDefaultWeakValue") ```
Which preprocessor define should be used to specify debug sections of code? Use#ifdef _DEBUGor#ifndef NDEBUGor is there a better way to do it, e.g.#define MY_DEBUG? I think_DEBUGis Visual Studio specific, is NDEBUG standard?
Visual Studio defines_DEBUGwhen you specify the/MTdor/MDdoption,NDEBUGdisables standard-C assertions. Use them when appropriate, ie_DEBUGif you want your debugging code to be consistent with theMS CRT debugging techniquesandNDEBUGif you want to be consistent withassert(). If you define your own debugging macros (and you don't hack the compiler or C runtime), avoid starting names with an underscore, as these are reserved.
I'm trying to programmatically send modified keystrokes, for instance a capital "A". The problem is that the shift modifier does not seem to have any effect. In my code, I have two events, one for the shift key down, and another for the 'm' key down. ``` CGEventRef mDown = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)46, true); CGEventRef shiftDown = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)56, true); CGEventPost(kCGAnnotatedSessionEventTap, shiftDown); CGEventPost(kCGAnnotatedSessionEventTap, mDown);} CFRelease(shiftDown); CFRelease(mDown); ``` The result is unfortunately always a small case 'm'! Any help would be appreciated.
You should be using CGEventKeyboardSetUnicodeString instead. Seeherefor some sample code.
I need to execute a unix command with different args in a loop. Now I wonder if I should use execvp(), passing in the cmd and the args, or use system, building a string consisting of cmd + args?
Well, the other answers aremostlycorrect. System, while not onlyforks and thenexecs, it doesn'texecyour process, it runs the default shell, passing your program as an argument. So, unless you really want a shell (for parameter parsing and the like) it ismuchmore efficient to do something like: ``` int i = fork(); if ( i != 0 ) { exec*(...); // whichever flavor fits the bill } else { wait(); // or something more sophisticated } ```
I have a listcontrol with three columns. I want to read what text is in the third column. I need this, because i want color this column according to that what text is in it. Can anyone tell me, how to read the data? Thanks in advance! kampi
If your control's associated CListCtrl is called m_listCtrl simply use: ``` CString colText = m_listCtrl.GetItemText(item, subitem); ``` You associate that variable with the control itself via something like this: ``` void CMyDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_LIST1, m_listCtrl); } ```
My function takes pointer*das parameter. I wrote that line -EXEC SQL VAR d->x is STRING;Actually I want a variable which can store the value ofd->x. with that variable i can manipulate some other work. I get the following error ``` Semantic error EXEC SQL VAR d->x is STRING; ``` Waiting for your suggestions.
If I were to guess, you want to have achararray, or acharpointer with enough memory, and then put your query string in it: ``` char query[BIG_ENOUGH]; sprintf(query, "EXEC SQL VAR %s is STRING;", d->x); ``` The above assumes that your have a string ind->x, and that you want the string value in your SQL query. I don't know if your SQL query is well-formed though. If this is not what you want, you need to post more information.
In a C program I get "passing argument ... from incompatible pointer type" warnings, however I want to get error and terminate compilation instead of warning. What flag shall I set in makefile?
If using gcc, I think the option combination you need is-fstrict-aliasing -Wstrict-aliasing=3 -Werror=strict-aliasing. Seethis textfor documentation of thestrict-aliasingoption.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed13 years ago. In recursive function, the variable should be declared as local or static or global variable? Thanks in advance...
It depends. A static variable means you have one variable that's shared across all recursive invocations. A normal local variable means each recursive invocation gets its own copy of that variable. You need to choose the one that makes sense for what you're doing. A global is like a static local variable (one variable shared by all invocations) but it's also visible to the rest of the application.
I am new to C and I am trying to figure out what the printf method does. I have this little bit of code and I keep getting errors when I use the %x for exampleprintf(“a) %x\n”, px);x% is for hex, Am i just using the wrong type here or is something else going on? what should the code I have below be printing out? ``` int x = 10; int y = 20; int *px = &x; int *py = &y; printf(“a) %x\n”, px); printf(“b) %x\n”, py); px = py; printf(“c) %d\n”, *px); printf(“d) %x\n”, &px); x = 3; y = 5; printf(“e) %d\n”, *px); printf(“f) %d\n”, *py); ```
Using integer formats (%x,%d, or the like) for printing pointers is not portable. So, for any of the pointer ones (px,py, and&px, but not*pxand*py), you should be using%pas your format instead.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed7 years ago.Improve this question There are several C libraries available for parsing JSON, that will compile on Linux. Which library would you recommend?
Just to close the loop: For the project in question, we ended up going withcJSON. We chose this one from the list of C libraries linked fromjson.org. Per the homepage, cJSON is: An ultra-lightweight, portable, single-file, simple-as-can-be ANSI-C compliant JSON parser, under MIT license. This happened to be a good fit for the particular project at hand, and the library worked out fine.
I am using chipmunk as a physics engine in my game. The problem is I now want to free all the children and then the space itself, so I can create a new space for the new level. I tried this: ``` cpSpaceFreeChildren(space); cpSpaceFree(space); ``` But it does not work and fails in: ``` cpHashSetReject(cpHashSet *set, cpHashSetRejectFunc func, void *data) { // Iterate over all the chains. for(int i=0; i<set->size; i++){ <-- here ``` Is there anything I need to clean up before calling this two methods?
I forgot to unschedule my tick: function that calls cpstep before freeing the space... It is working now.
I'm trying to do the safe thing, and have a program that needs to runs as root to drop its privileges when it doesn't need them. This works well if Ichmodmy binary with the SUID bit, and make it belong to root, as now I have UID = some user, and EUID = root, so I can useseteuid(0)andseteuid(getuid())to respectively raise and drop admin rights. But if I usesudoinstead of setting the SUID, then UID == EUID == 0, and so callingseteuid(getuid())won't have any effect. And I can't just changeUIDto some value from some random user, as thesetuid()man page clearly states that if it is called from a program running as root, one loses the privileges for good, with no hope of getting them back. So, how do I make my program lose temporarily its privileges when run usingsudo?
seteuid(some random uid)to drop privileges,seteuid(0)to get them back, when running asroot.
I was working on this program and I noticed that using %f for a double and %d for a float gives me something completely different. Anybody knows why this happens? ``` int main () { float a = 1F; double b = 1; printf("float =%d\ndouble= %f", a, b); } ``` This is the output ``` float = -1610612736 double = 190359837192766135921612671364749893774625551025007120912096639276776057269784974988808792093423962875123204096.0000 ```
%dstands for decimal and it expects an argument of typeint(or some smaller signed integer type that then gets promoted). Floating-point typesfloatanddoubleboth get passed the same way (promoted todouble) and both of them use%f. In C99 you can also use%lfto signify the larger size ofdouble, but this is purely cosmetic (notice that withscanfno promotion occurs and this actually makes a difference).
How would you set a variable to equal infinity (or any guaranteed largest number value) in C?
``` #include <limits.h> int x = INT_MAX; ``` EDIT: answered before the questioner clarified, I was just guessing what type they wanted.
Years ago, in my long lost copy of Charles Petzold's Windows 3.0 Programming book, there was a magic COLORREF or RGB value documented that you could use to check whether you should draw text in a light colour or a dark colour. E.g. if the background colour was below this value, then use black text, if it was higher, use white text. Does anyone know/remember what this magic value is?
I can't tell about COLORREF but I've got good results using theluminanceas threshold: ``` Y= 0.3 * R + 0.59 * G + 0.11 * B ``` with colours expressed as a decimal value between 0.0 and 1.0. If Y>=0.5 I considered the background "light" (and used dark text), if Y<0.5 I did the opposite. I remember I also used other formulas including the simple mean: ``` L = (R+G+B)/3 ``` but I didn't like the result. It seems logical to me that Green contributes to lightness more than Red and Red more than Blue.
Why doesn't this work? When I try to use -l or -s as the first argument, the if statements don't take. They always go to the else statement. ``` #include <stdio.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <stdlib.h> int main(int argc, char* argv[]) { if (argv[1] == "-l") { printf("Yay!\n"); } else if (argv[1] == "-s") { printf("Nay!\n"); } else { printf("%s\n", argv[1]); } return 0; } ```
You cannot compare strings using==operator - usestrcmp()instead. By comparing strings using==you are comparing the addresses ofchar *pointers, not string values.
If we consider recursive function in C/C++, are they useful in any way? Where exactly they are used mostly? Are there any advantages in terms of memory by using recursive functions? Edit: is the recursion better or using a while loop?
Recursive functions are primarily used for ease of designing algorithms. For example you need to traverse a directory tree recursively - its depth it limited, so you're quite likely to never face anything like too deep recursion and consequent stack overflow, but writing a tree traversal recursively is soo much easier, then doing the same in iterative manner. In most cases recursive functions don't save memory compared to iterative solutions. Even worse they consume stack memory which is relatively scarse.
Im working in a memory restricted environment and need to create strings dynamically, but still have them not take up heap memory. So does this make sense: ``` static char staticStringBuffer[10240]; static size_t staticStringWatermark = 0; void createString( const char * something, const char * somethingElse ) { char buf[1024]; strcat(buf, "test"); strcat(buf, something); strcat(buf, somethingElse); strcat(&staticStringBuffer[staticStringWatermark], buf); staticStringWatermark += strlen(buf+1); } ``` This probably dosent compile, but is what I am attempting sane - sacrificing static memory for heap memory? Thank-you ^_^
That of course depends on what your particular environment does when it loads your program; where is the program's static data put? On many operating systems, the program is loaded into heap memory and run from there, so your static data will still end up on the heap.
If I have a C file like below, what is the difference betweeniandj? ``` #include <stdio.h> #include <stdlib.h> static int i; int j; int main () { //Some implementation } ```
ihas internal linkage so you can't use the nameiin other source files (strictly translation units) to refer to the same object. jhas external linkage so you can usejto refer to this object if you declare itexternin another translation unit.
How come I can do this: ``` char sXSongs[20][30] = {"Song 1", "Song 2 (w/Blur)", "The End (It's Not Here Yet)"}; addAlbum(&list, "The Beatles", "Some Famous CD", 1960, sXSongs); ``` But not this: ``` addAlbum(&list, "The Beatles", "Some Famous CD", 1960, {"Song 1", "Song 2 (w/Blur)", "The End (It's Not Here Yet)"}); ``` Is it impossible to initialize an array of cstrings inside a function call? Here are some other tidbits of information: ``` album* list = NULL; typedef struct album { char performer[20]; char CDtitle[50]; int year; char songs[20][30]; struct album* prev; struct album* next; } album; ```
No. It is possible to initialize an array when declaring it, not otherwise.
Is it a good practice to group all the variables of same type together while declaring in local scope within a function? If yes, why? Does it solve memory alignment issues?
I think it mattered with the VAX C compiler I used 20 years ago, but not with any modern compiler. It isnotsafe to assume that local variables will be in any particular order, certainly not safe to assume they will be in the order you declared them. I havedefinitelyseen the MSVC compiler reorder them. Grouping variables of the same typedoeshelp when they are fields of a struct, because the ordering of fields of a struct is guaranteed to match the order of declaration.
Please explain this type signature :void (*signal(int signo, void *(func)(int)))(int)
The type signature of thesignalfunction is a bit more clear when a typedef is used for the function pointers that are passed around: ``` typedef void (*sighandler_t)(int); sighandler_t signal(int signo, sighandler_t func); ``` sighandler_tis a pointer to a function that takes anintparameter and returns nothing. Thesignalfunction takes such a function pointer as its second parameter. It also returns a function pointer of that type.
I have to submit code to one of the problems in ACM IPC and, as you may know, the time counts a lot. So, I have to read efficiently an input like this: The first line will contain the sequence of integer values associated and the second line will contain the sequence of integer values associated with another sequence. E.g.: ``` 3 2 1 4 5 7 6 3 1 2 5 6 7 4 7 8 11 3 5 16 12 18 8 3 11 7 16 18 12 5 255 255 ``` I have to put the 1st line in an array and the second in another and pass both in a function. How do I read and put these in C/C++? I was thinking in a C way, but my approach would have 2 while's... I have preference reading with scanf, but the parsing can be done as you want. Please , help this newb!
Read the lines usingstd::getline(). Then use astd::stringstreamto parse each line. As this is for a competition, you won't be wanting actual code.
In my C++ program, I want to make sure i can write info to a file. How can I perform this check?
The only sure way to find if you can write to a file is to try to write to a file. It is possible, and even likely in some circumstances, that a file will have its permissions changed between calls to function such as stat and the actual write. Your code must deal with write failures anyway, so it makes sense to centralise the testing code there.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed4 years ago.Improve this question I want to make some GUI mockup program for video player, so my idea is just to show some menu pictures over real video being playback. I have working program made with C and SDL just to load pictures and make a slideshow, but i don´t know how to put this over video with transparencies. Do you have a hint? ps. i usually program with python and C, so if there is any solution with this two i highly appreciate. Thanks!
Suggestion: use Openframeworks http://www.openframeworks.cc/documentation It is in C++ though, and not C. Check the documentation for class ofVideoPlayer
i need to check that a given point is present or not in the given region of a circle how can i do so is there any function in ansi c to help me?
Do you want to check if point belongs to a circle or in some subregion in the circle? To check if point belongs to the circle you can simply check if the distance from this point to the circle center is less then circle radius. ``` if ((point.x - center.x)*(point.x - center.x) + (point.y - center.y)*(point.y - center.y) < radius*radius) // point is inside circle ```
Is it possible to specify per-thread in Linux?
Yes, you kinda can do that. However not per-thead, but only per-call, using locale_t structures. Read more about that at POSIX: http://www.opengroup.org/onlinepubs/9699919799/functions/newlocale.html And Ulrich Dreppper's dedsgin documents of what whent into glibc 2.1: http://people.redhat.com/drepper/tllocale.ps.gz
In case of Linux, for time functions we have a _r versions Ex: localtime has localtime_r, but in Windows I am unable to find some such functions. Are the Windows time functions inherently thread-safe?
With Microsoft Visual Studio you have a choice of c-runtimes to use: typically they were: static single threaded library (libc)Static multithreaded library (libcmt)dynamic multithreaded library (msvcrt) The multithreaded libraries are thread safe. The single threaded library was last seen in MSVC 2005 and has been dropped from MSVC 2008. The dll runtime (msvcrt.dll) just has to be thread safe - As the implementation is in a dll and therefore shared between multiple other modules in the process, all of which could be using worker threads, It has to be threadsafe as there would be no sane way to design an application to use it otherwise.
What is the difference between a re-entrant function and a thread safe function?
Re-entrant means no global state (local only). Thread safe means it is not possible for 2 (or more) threads to conflict with each other (by writing conflicting values).
I want to know the logic behind this statement, the proof. The C expression -x, ~x+1, and ~(x-1) all yield the same results for any x. I can show this is true for specific examples. I think the way to prove this has something to do with the properties of two's complement. Any ideas?
Consider what you get when you add a number to its bitwise complement. The bitwise complement of an n-bit integer x has a 1 everywhere x has a 0, and vice versa. So it's clear to see: x + ~x = 0b11...11 (n-bit value of all ones) Regardless of the number of bits in x. Further, note that adding one to an n-bit number filled with all ones will make it wrap to zero. Thus we see: x + ~x + 1 = 0b11...11 + 1 = 0 and ~x + 1 = -x. Similarly, note (x - 1) + ~(x - 1) = 0b11...11. Then (x - 1) + ~(x - 1) + 1 = 0, and ~(x - 1) = -x.
I am using fprintf command for writing on the text file, but every time when the function called its remove the previous data, I actually want to update the file so that the previous data remain. Kindly guide me how I can make it possible?
when you open the file use "a" for append. ``` FILE * file = fopen("filename", "a"); ``` http://www.cplusplus.com/reference/clibrary/cstdio/fopen/
I need code for rotating an image in C++ which functions like imrotate function of matlab. Please suggest a good link. Or if someone can provide the code for imrotate. Or at least please explain the algorithm. Its not a homework. I need this code for my project. And we can use any external library or code.
OpenCV2.0has several computer vision and image processing tools. SpecificallywarpAffine(by defining the rotation matrix) will solve your problem with rotating an image. The 2x3 transformation matrix mentioned in the documentation is as follows: where θ is the angle of rotation and txand tyis the translation along thexandyaxes respectively. You can get the source codehere. Also, OpenCV2.0 hasmanyMATLAB-esque functions likeimread, etc.
I was thinking of trying OpenCV for a project and noticed that it had C, C++ and Python. I am trying to figure out whether I should use C++, C or Python -- and would like to use whatever has the best OpenCV support. Just from looking at the index page for the various documentation it looks like the C++ bindings might have more features than the others? Is this true? If C++ has more bindings, it seems that would be a more obvious choice for me, but I was just curious if it really has more features, etc than the others? Thanks!
Actually Python binding was finishedstarting with release 2.2. So i would go with python if i were you, because the performance will be almost the same anyway as you are using c libraries in both cases. However python will get you there faster, safely and you will spend more time on your algorithm rather than getting things to build and run not mentioning memory management hassles
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed7 years ago.Improve this question There are several C libraries available for parsing JSON, that will compile on Linux. Which library would you recommend?
Just to close the loop: For the project in question, we ended up going withcJSON. We chose this one from the list of C libraries linked fromjson.org. Per the homepage, cJSON is: An ultra-lightweight, portable, single-file, simple-as-can-be ANSI-C compliant JSON parser, under MIT license. This happened to be a good fit for the particular project at hand, and the library worked out fine.
I am using chipmunk as a physics engine in my game. The problem is I now want to free all the children and then the space itself, so I can create a new space for the new level. I tried this: ``` cpSpaceFreeChildren(space); cpSpaceFree(space); ``` But it does not work and fails in: ``` cpHashSetReject(cpHashSet *set, cpHashSetRejectFunc func, void *data) { // Iterate over all the chains. for(int i=0; i<set->size; i++){ <-- here ``` Is there anything I need to clean up before calling this two methods?
I forgot to unschedule my tick: function that calls cpstep before freeing the space... It is working now.
I'm trying to do the safe thing, and have a program that needs to runs as root to drop its privileges when it doesn't need them. This works well if Ichmodmy binary with the SUID bit, and make it belong to root, as now I have UID = some user, and EUID = root, so I can useseteuid(0)andseteuid(getuid())to respectively raise and drop admin rights. But if I usesudoinstead of setting the SUID, then UID == EUID == 0, and so callingseteuid(getuid())won't have any effect. And I can't just changeUIDto some value from some random user, as thesetuid()man page clearly states that if it is called from a program running as root, one loses the privileges for good, with no hope of getting them back. So, how do I make my program lose temporarily its privileges when run usingsudo?
seteuid(some random uid)to drop privileges,seteuid(0)to get them back, when running asroot.
I was working on this program and I noticed that using %f for a double and %d for a float gives me something completely different. Anybody knows why this happens? ``` int main () { float a = 1F; double b = 1; printf("float =%d\ndouble= %f", a, b); } ``` This is the output ``` float = -1610612736 double = 190359837192766135921612671364749893774625551025007120912096639276776057269784974988808792093423962875123204096.0000 ```
%dstands for decimal and it expects an argument of typeint(or some smaller signed integer type that then gets promoted). Floating-point typesfloatanddoubleboth get passed the same way (promoted todouble) and both of them use%f. In C99 you can also use%lfto signify the larger size ofdouble, but this is purely cosmetic (notice that withscanfno promotion occurs and this actually makes a difference).
How would you set a variable to equal infinity (or any guaranteed largest number value) in C?
``` #include <limits.h> int x = INT_MAX; ``` EDIT: answered before the questioner clarified, I was just guessing what type they wanted.
Years ago, in my long lost copy of Charles Petzold's Windows 3.0 Programming book, there was a magic COLORREF or RGB value documented that you could use to check whether you should draw text in a light colour or a dark colour. E.g. if the background colour was below this value, then use black text, if it was higher, use white text. Does anyone know/remember what this magic value is?
I can't tell about COLORREF but I've got good results using theluminanceas threshold: ``` Y= 0.3 * R + 0.59 * G + 0.11 * B ``` with colours expressed as a decimal value between 0.0 and 1.0. If Y>=0.5 I considered the background "light" (and used dark text), if Y<0.5 I did the opposite. I remember I also used other formulas including the simple mean: ``` L = (R+G+B)/3 ``` but I didn't like the result. It seems logical to me that Green contributes to lightness more than Red and Red more than Blue.
Why doesn't this work? When I try to use -l or -s as the first argument, the if statements don't take. They always go to the else statement. ``` #include <stdio.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <stdlib.h> int main(int argc, char* argv[]) { if (argv[1] == "-l") { printf("Yay!\n"); } else if (argv[1] == "-s") { printf("Nay!\n"); } else { printf("%s\n", argv[1]); } return 0; } ```
You cannot compare strings using==operator - usestrcmp()instead. By comparing strings using==you are comparing the addresses ofchar *pointers, not string values.
If we consider recursive function in C/C++, are they useful in any way? Where exactly they are used mostly? Are there any advantages in terms of memory by using recursive functions? Edit: is the recursion better or using a while loop?
Recursive functions are primarily used for ease of designing algorithms. For example you need to traverse a directory tree recursively - its depth it limited, so you're quite likely to never face anything like too deep recursion and consequent stack overflow, but writing a tree traversal recursively is soo much easier, then doing the same in iterative manner. In most cases recursive functions don't save memory compared to iterative solutions. Even worse they consume stack memory which is relatively scarse.
Im working in a memory restricted environment and need to create strings dynamically, but still have them not take up heap memory. So does this make sense: ``` static char staticStringBuffer[10240]; static size_t staticStringWatermark = 0; void createString( const char * something, const char * somethingElse ) { char buf[1024]; strcat(buf, "test"); strcat(buf, something); strcat(buf, somethingElse); strcat(&staticStringBuffer[staticStringWatermark], buf); staticStringWatermark += strlen(buf+1); } ``` This probably dosent compile, but is what I am attempting sane - sacrificing static memory for heap memory? Thank-you ^_^
That of course depends on what your particular environment does when it loads your program; where is the program's static data put? On many operating systems, the program is loaded into heap memory and run from there, so your static data will still end up on the heap.
If I have a C file like below, what is the difference betweeniandj? ``` #include <stdio.h> #include <stdlib.h> static int i; int j; int main () { //Some implementation } ```
ihas internal linkage so you can't use the nameiin other source files (strictly translation units) to refer to the same object. jhas external linkage so you can usejto refer to this object if you declare itexternin another translation unit.
How come I can do this: ``` char sXSongs[20][30] = {"Song 1", "Song 2 (w/Blur)", "The End (It's Not Here Yet)"}; addAlbum(&list, "The Beatles", "Some Famous CD", 1960, sXSongs); ``` But not this: ``` addAlbum(&list, "The Beatles", "Some Famous CD", 1960, {"Song 1", "Song 2 (w/Blur)", "The End (It's Not Here Yet)"}); ``` Is it impossible to initialize an array of cstrings inside a function call? Here are some other tidbits of information: ``` album* list = NULL; typedef struct album { char performer[20]; char CDtitle[50]; int year; char songs[20][30]; struct album* prev; struct album* next; } album; ```
No. It is possible to initialize an array when declaring it, not otherwise.
Is it a good practice to group all the variables of same type together while declaring in local scope within a function? If yes, why? Does it solve memory alignment issues?
I think it mattered with the VAX C compiler I used 20 years ago, but not with any modern compiler. It isnotsafe to assume that local variables will be in any particular order, certainly not safe to assume they will be in the order you declared them. I havedefinitelyseen the MSVC compiler reorder them. Grouping variables of the same typedoeshelp when they are fields of a struct, because the ordering of fields of a struct is guaranteed to match the order of declaration.
Please explain this type signature :void (*signal(int signo, void *(func)(int)))(int)
The type signature of thesignalfunction is a bit more clear when a typedef is used for the function pointers that are passed around: ``` typedef void (*sighandler_t)(int); sighandler_t signal(int signo, sighandler_t func); ``` sighandler_tis a pointer to a function that takes anintparameter and returns nothing. Thesignalfunction takes such a function pointer as its second parameter. It also returns a function pointer of that type.
I'm working on a project that's supposed to work on both Windows and Linux (with an unofficial Mac port as well) that emulates a true colour system console. My problem is that recently there appeared a request for textfield support (yes, console-based) and it would be cool to add the possibility of copying text to clipboard and pasting from it. Is there a way of achieving this that will: be done in C (not C++),work in both Windows and in Linux (preprocessor macros are an option if there's no platform-independent code),require no extra libraries to link to? Thanks in advance for your help.
If you're not using a cross platform UI library (like wx or something), then it sounds like you're just going to have to write native clipboard code for each platform you want to support. Remember, on Macintoshes, you copy with Command-C, not Ctrl+C :)
Callingsystem()to run an external .exe and checking error code upon errors: ``` #include <errno.h> #include <stdlib.h> function() { errno_t err; if( system(tailCmd) == -1) //if there is an error get errno { //Error calling tail.exe _get_errno( &err ); } } ``` First two compile errors: ``` error C2065: 'err' : undeclared identifier error C2065: 'errno_t' : undeclared identifier ``` Not sure why as I am including therequired and optional header files?Any help is appreciated. Thank You.
A typical usage is like: ``` if (somecall() == -1) { int errsv = errno; printf("somecall() failed\n"); if (errsv == ...) { ... } } ``` which is taken fromhere.
I have command line utility written in ANSI C on a Mac with a function to create a bubble sorted array for a single-linked list. I declared the loop variables. ``` int a = 0; int b = 0; ``` I wrote the bubble sort for loops in the abbreviated style (i.e., leaving the variable initialization empty). ``` for ( ; a < size; a++) for( ; b < size; b++) ``` This executed only once before exiting. A previous for loop using the i variable to populate the array was written the same way and executed as expected. The fix for the bubble sort loops was to put a = 0 and b = 0 back in. Is there a reason why the abbreviated for loops failed to execute?
If you leave out theb=0the inner loop will run exactly once, because after that b is already equal to size. You need to reset b to 0 on each iteration of the inner loop.
CreateProcess()came up a few times searching google....Is it OK to assume this is the safest and most efficient method?If so, I would like to use the output of the called process.How do I know it has completed before continuing on in the C program? Thanks.
ShellExecuteCan be used to create a process, its a more convenient way to pass arguments. But if you want to use the output of the process thenCreateProcessis probably your best bet WithCreateProcessyou can pass aSTARTUPINFOstructure that can be used to pass a file pipe handle to Standard Out of the process. CreateProcesswill return aPROCESS_INFORMATIONstructure containing a HANDLE to the created process. That handle will become signalled when the process exits. So You canWaitForSingleObjecton the process handle to wait for the output to be complete. Don't forget toCloseHandleon the process handle and thread handle when you are done.
File 1: ``` static char* const path; //GLOBAL int main() { path = FunctionReturningPath(); UsePath() } ``` File 2: ``` extern char* const path; //GLOBAL from file 1 UsePath() //function using global { something = path; } ``` (Pseudo) Would like to use path in file 2.I'm defining the global within main in file 1, is that bad practice using a global? and doesn't compile: ``` Compile Error: error LNK2001: unresolved external symbol _path ``` Any help is appreciated. Thank You.
``` static char* path; //GLOBAL ``` Wrong. making it static means it is local to the file, and cannot be exposed using extern. You want: ``` char* path; //GLOBAL ```
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 help centerfor guidance.Closed10 years ago. What is the standard/best reference card forcscopeshortcuts/usage that I can print for quick reference?
The easiest way I can think of doing this, and its cheap, is to get the hardcopy man page for cscope and create a text file...for instance: ``` $ man cscope | col -b > cscope.txt ``` Or, to convert to ps file for feeding into Ghostscript: ``` $ man -t cscope > cscope.ps $ gs cscope.ps -sOutputFile=cscope.pdf ```
When I do#include <stat.h>in Linux, I get a compiler error. I need this library for theS_IWRITEflag, which in its turn is used in the context of system-level IO. Is stat.h unavailable in Linux?
stat.h is available under the "sys" folder, try to #include it from there or add it to the list of include directories.
I have a collection of dynamic libraries that I want to link to in /usr/local/lib, how can I do this using gcc without setting my LD_LIBRARY_PATH (i have heard it is bad to do this fora number of reasons). I have spent an hour looking at this on the internet, and fiddling with command line arguments, the only way I got it to work was using the -static -I/usr/local/lib/ flag, but this converts dynamic libraries to static libraries, and the compiler throws up some warnings. Thanks for your help
Add/usr/local/libto the loader configuration in/etc/ld.so.confand runldconfig.
Can astaticfunction in C be potentially faster because the compiler's optimizer sees all the call sites and therefore optimizes the epilog and prolog of the called function?
It in theory it can. Yet at the same time some modern compilers can perform so called "global optimizations", which are based on analyzing relationships between the code across translation units. This can include analyzing all the call sites for a given function in the entire program (as opposed to a single translation unit) and potentially extend such optimizations to non-static functions as well.
I'm printing a string(char *) in gdb ``` (gdb) p l l=0x9aa1f48 "up2 129104596496602200 19 0 0 3 0 eth1 XX :001CB",'0' <repeats 12 times>, "DC" ``` Is there a setting to havepprint the whole string and not fill inn the "repeats ... ". While at it - also extend the default printable length of a string,pseems to cut off if the string is quite long.
``` set print repeats 0 ``` Example: ``` (gdb) p "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" $6 = 'a' <repeats 30 times> (gdb) set print repeats 0 (gdb) p "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" $7 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" (gdb) set print repeats 10 (gdb) p "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" $8 = 'a' <repeats 30 times> ```
This code compiles, but no surprises, it fails while linking (no main found): Listing 1: ``` void main(); ``` Link error: \mingw\lib\libmingw32.a(main.o):main.c:(.text+0x106) undefined reference to _WinMain@16' But, the code below compiles and links fine, with a warning: Listing 2: ``` void (*main)(); ``` warning: 'main' is usually a function Questions: In listing 1, linker should have complained for missing "main". Why is it looking for _WinMain@16?The executable generated from listing 2 simply crashes. What is the reason? Thanks for your time.
True,maindoesn't need to be a function. This has been exploited in some obfuscated programs that contain binary program code in an array calledmain. The return type of main() must beint(notvoid). If the linker is looking forWinMain, it thinks that you have a GUI application.
I tried printf("%d, %d\n", sizeof(char), sizeof('c')); and got1, 4as output. If size of a character is one, why does'c'give me 4? I guess it's because it's an integer. So when I dochar ch = 'c';is there an implicit conversion happening, under the hood, from that 4 byte value to a 1 byte value when it's assigned to the char variable?
In C 'a' is an integer constant (!?!), so 4 is correct for your architecture. It is implicitly converted to char for the assignment. sizeof(char) is always 1 by definition. The standard doesn't say what units 1 is, but it is often bytes.
i would like to know the function which returns the drive where the windows has been installed. for example if we run a program with following code in windows which is installed in "C:\" temp_char = getWindowsInstalledDrive(); should return "C:\". please point me to that function if you know. it should be a C/C++ function. Thanks.
You can use GetSystemDirectory():http://msdn.microsoft.com/en-us/library/ms724373%28VS.85%29.aspxand then take the first 3 letters.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed8 years ago.Improve this question Let's say I have a simple config file that my c program needs to read/parse. Let's say it looks a little bit like this: ``` #Some comment key1=data1 key2=data2 ``` Is there a standard c lib that I can use instead of writing my own parser? Thanks Johan Note: Today I have my own little parser, but there must be some standard libs that solves this simple problem.
libconfigbut it does quite more than what you're asking
Yes, this is a really lazy question but I figure this is problem that people have often enough that someone here would have something already written to share. I have a ton of C files with#includestatements using Windows relative paths. I'm working on compiling the code on other operating systems (immediately, on my OS X development machine) and need to replace all the backslashes with forward slashes in these include statements. So, from something like#include "libs\helper.h"to#include "libs/helper.h".
``` sed '/^[ ]*#[ ]*include/ s:\\:/:g' ``` This should be pretty robust as it should catch any legal format of#includebut not anything else.