problem about stdlib-Collection of common programming errors
cdleary
c math stdlib
The negative implication of this is noted in the man page:NOTESTrying to take the absolute value of the most negative integer isnotdefined.What’s the reasoning behind this and what’s the best recourse for a person who would like to avoid undefined behavior? Do I have to resort to something like:unsigned uabs(signed val) {return val > 0? val: (val == 1U << ((sizeof(val) * 8) – 1))? -1U: -val; }(Intentionally hacky to emphasize displeasure with stdlib ;-)ExampleSay you had a 4-bit signe
Rafael S. Calsaverini
random stdlib gsl boost-random
I’m making a monte carlo simulation in C++ and I was using Boost for random numbers. I used GSL a bit too. But it turns out random number generation is one of my biggest runtime inefficiencies, so I just started using good old rand() from cstdlib. How badly am I risking to have poor random number properties on my simulation? I use around 10^6 or 10^7 random number samples.
Shahbaz
c++ stdlib
My Question is related to this as I solved the problem, I wrote my own sorting algorithm (a simple insertion sort), and it works. I am quite surprised by this as I thought that the standard library is well-tested. Are there any known special cases in which std::sort might mess up?
bogdan
c++ stdlib
I have a function foo(const std::string& str); that it does crash if you call it using foo(NULL).What can I do to prevent it from crashing?
Mark E
c stdlib strtol
I was making some proves with strtol() from stdlib library because i had a program that always crashed and i found that this worked perfectly:main(){ char linea[]=”0x123456″,**ap; int num; num=strtol(linea,ap,0); printf(“%d\n%s”,num,*ap); }But when I added just a new declaration no matter where it crashed like thismain(){ char linea[]=”0x123456″,**ap; int num; num=strtol(linea,ap,0); printf(“%d\n%s”,num,*ap); int k; }just adding that final “int k;” the program crashed at executing strtol() can’t
Job
c++ stl stdlib
Let me start with explaining what I mean with “magic”. I will use two examples from Java:Every class inherits (directly or indirectly) the Object class. Operator overloading is not supported by Java but the + operator is defined for String objects.This means that it is impossible to make an implementation of the Object and String classes in pure(*) Java. Now this is what I mean with “magic”: to make an implementation of these classes, you will need some special support from the compiler.What I a
Michal Sznajder
c stdlib qsort programming-pearls
is it just me or this code in Programming Pearls is wrong (quicksort wants 2 const voids, no?) If so, is my solution right? Apologies, just learning…int wordncmp(char *p, char* q) { int n = k;for ( ; *p == *q; p++, q++)if (*p == 0 && –n == 0)return 0;return *p – *q; }int sortcmp(char **p, char **q) { return wordncmp(*p, *q); } …qsort(word, nword, sizeof(word[0]), sortcmp);Is this a solution?int sortcmp(const void *p, const void *q) { return wordncmp(* (char * const *) p, * (ch
Chris Metzler
c++ version backwards-compatibility stdlib
I’m working on a 64-bit Linux system, trying to build some code that depends on third-party libraries for which I have binaries. During linking, I get a stream of undefined reference errors for one of the libraries, indicating that the linker couldn’t resolve references to standard C++ functions/classes, e.g.: librxio.a(EphReader.o): In function `gpstk::EphReader::read_fic_data(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)’: EphReader.cpp:(
pmr
c++ stdlib
I recently wondered about the behavior of modifying sequence container operations (e.g. insert, erase) when called with iterators that refer to elements not controlled by the container whose member function is called.int main() {std::vector<int> a = {1,2,3}, b = {1,2,3};a.erase(b.begin()); }I know that this will lead to undefined behavior, but where exactly is this forbidden by the standard?(The “controlled by” terminology is what is used in the Dinkumware documentation and is also used in
user397232
stdlib
I searched on internet and saw a lot of code that uses itoa() function & they claimed that this function is in stdlib.hI’m using 2 versions of GCC right now:(GCC) 4.2.4 (Ubuntu 4.2.4-1ubuntu4)) (GCC) 4.1.2 20080704 (Red Hat 4.1.2-44)and both of them does not have itoa() function (I compile the program & error: undefined reference to `itoa’).Any ideas? Thanks.
Joel Barba
c++ c++0x atomic stdlib
I’m attempting to implement the atomic library from the C++0x draft. Specifically, I’m implementing §29.6/8, the store method:template <typename T> void atomic<T>::store(T pDesired, memory_order pOrder = memory_order_seq_cst);The requirement states:The order argument shall not be memory_order_consume, memory_order_acquire, nor memory_order_acq_rel.I’m not sure what to do if it is one of these. Should I do nothing, throw an exception, get undefined behavior, or do something else?P.S.
Dan
c++ visual-studio-2010 g++ stdlib
I have this very simple piece of code;#include <deque> #include <vector>using namespace std;class A { public:A(){};~A(){};deque<A> my_array; // vector<A> my_array; };int main(void) { }If I compile this code with both g++ and icc/icpc on linux it compiles fine, even with -Wall it gives no warnings. If I swap the deque to a vector the situation is the same.I would like to build this code on windows using MSVCC (cl) but unfortunately it throws error c2027:error C2027: use of
Lightness Races in Orbit
c++ c++11 language-lawyer stdlib
Following on from my previous question, can we prove that the standard allows us to pass an empty range to a standard algorithm?Paragraph 24.1/7 defines an “empty range” as the range [i,i) (where i is valid), and i would appear to be “reachable” from itself, but I’m not sure that this qualifies as a proof. In particular, we run into trouble when looking at the sorting functions. For example, std::sort:Complexity: O(N log(N)) (where N == last – first) comparisonsSince log(0) is generally consider
Bala
c gcc stdlib atof
Hopefully this is a very simple question. Following is the C pgm (test.c) I have. #include <stdio.h> //#include <stdlib.h>int main (int argc, char *argv[]) {int intValue = atoi(“1”);double doubleValue = atof(“2″);fprintf(stdout,”The intValue is %d and the doubleValue is %g\n”, intValue, doubleValue);return 0; }Note that I am using atoi() and atof() from stdlib.h, but I do not include that header file. I compile the pgm (gcc test.c) and get no compiler error!I run the pgm (./a.out) an
lron
c file-io line stdlib
I wrote this function to read a line from a file:const char *readLine(FILE *file) {if (file == NULL) {printf(“Error: file pointer is null.”);exit(1);}int maximumLineLength = 128;char *lineBuffer = (char *)malloc(sizeof(char) * maximumLineLength);if (lineBuffer == NULL) {printf(“Error allocating memory for line buffer.”);exit(1);}char ch = getc(file);int count = 0;while ((ch != ‘\n’) && (ch != EOF)) {if (count == maximumLineLength) {maximumLineLength += 128;lineBuffer = realloc(lineBuffer
LordOphidian
c stdlib lynxos
It seems that LynxOS’s implementation of strtod doesn’t handle all the same cases as that of Linux, or for that matter Solaris. The problem I have is that I am trying to parse some text that can have decimal or hexadecimal numbers in it.On Linux I call a = strtod(pStr, (char **)NULL);and I get the expected values in a for input strings such as 1.234567 and 0x40.On LynxOS, the decimal numbers parse correctly, but the hex parses simply as 0 due to stopping when it hits the ‘x’. Looking at the man
highsciguy
c linux string stdlib
I am on a (ubuntu precise) linux system and I want to remove leading characters (tabulators) from a string in C. I thought the following code was working on my previous installation (ubuntu oneric) but I found now that it does not work anymore (note that this is a simplified version of a code for general UTF-8 characters):#include <math.h> #include <stdlib.h> #include <stdio.h> #include <string.h>int main() {int nbytes = 10000;char *my_line, *my_char;my_line = (char *)mal
SunnyShah
c stdlib
char * val; val = getenv(“ENV_VAR_NAME”);above is a code to get environment variable, will it cause memory leak if I dont free memory returned by getenv(char*) ? If no then please answer why?
JXG
c string null stdlib
There are many endearing string functions in the C standard library, such as (in string.h)char *strcat(char *str1, const char *str2);or (in stdlib.h)long int strtol(const char *nptr, char **endptr, int base);(Ignore the wisdom of calling these functions, for the purposes of this question.)What will happen if I pass any of these functions a NULL pointer? (I mean (char *) 0, not the empty string.)I haven’t found any answers in the man pages or on the web. This leads me to think it’s implementati
ildjarn
c++ visual-c++ visual-studio-11 stdlib
#include <string> #include <cstdio> int main() {std::string s = “12345678”;std::printf(“[%s]\n”, s); }Here is an obvious typo of missing “.c_str()”. But VS2011 even with /Wall doesn’t emit any warnings, and the program works. If to compile this code in gcc, it says “warning: cannot pass objects of non-POD type ‘struct std::string’ through ‘…’; call will abort at runtime” and the program crashes with “Illegal instruction”.Did they really implement a trick in VS STL to make programs
Antonio Pérez
c++ visual-c++ stl stdvector stdlib
I am not sure what’s wrong with this code :std::vector<int> myVector(0);if (myVector.back() == 12)myVector.push_back(12);It seems that calling back() on an empty vector crashes the program. I don’t understand why it’s crashing? Do we need to check the length of the vector before calling back()? or is possible that it’s a bug? The documentation says, that if the vector is empty it return an undefined value.
Lightness Races in Orbit
c++ c++11 stdlib
Consider standard algorithms like, say, std::for_each.template<class InputIterator, class Function> Function for_each(InputIterator first, InputIterator last, Function f);As far as I can tell, there is actually no requirement placed on the relative states of the two InputIterator arguments.Does that mean that the following is technically valid? Or is it undefined? What can I realistically expect it to do?std::vector<int> v{0,1,2,3,4}; std::for_each(v.begin()+3, // range [3,0)v.begin
Norcalli
c++ clang stdlib undefined-reference libc++
The first couple are too long to reference. I get this error when I try to compile clang++ -stdlib=libc++ ../main.cc … with clang and libc++ from the SVN.error: undefined reference to ‘typeinfo for char const*’ error: undefined reference to ‘__cxa_allocate_exception’ error: undefined reference to ‘__cxa_throw’ /tmp/cc-pbn00y.o:../main.cc:function std::__1::deque<double, std::__1::allocator<double> >::__add_back_capacity(): error: undefined reference to ‘__cxa_begin_catch’ /tmp/cc-
Web site is in building