I am facing a problem with shrink_to_fit() function of STL C++. The problem is which I use it, the compiler gives error "Method 'shrink_to_fit' could not be resolved" on Eclipse Luna (32 bit) with MinGW compiler but the same program works fine in Dev C++.
Image of the program:
Error:
Compiler do not recommend shrink_to_fit() after using dot(.):
Original code:
#include <iostream>
#include <vector>
using namespace std;
int main(void) {
vector<int> v(128);
cout << "Initial capacity = " << v.capacity() << endl;
v.resize(25);
cout << "Capacity after resize = " << v.capacity() << endl;
v.shrink_to_fit();
cout << "Capacity after shrink_to_fit = " << v.capacity() << endl;
return 0;
}
Please let me know is this my fault or IDE's.
P.S. I am using C++14.
It works fine for me (with -std=c++11 flag, and MinGW distro from https://nuwen.net/mingw.html#install) on
Eclipse IDE for C/C++ Developers,
Version: 2019-09 R (4.13.0)
Build id: 20190917-1200
OS: Windows 10, v.10.0, x86_64 / win32
Java version: 13.0.1
as well as on Linux (with -std=c++11 flag and GCC 7.4.0 compiler). It could be a problem with your IDE, compiler (with right flag) or STL implementation. There can't be a 4th reason in my view.
Works fine for me.
Try compile 'by hand' to find out if it is about the ide:
g++ foo.cpp -o foo
./foo
Related
I'm using gcc 10.1 on Ubuntu 18.04. I'm getting segfaults when defining a large stack allocated variable, even though my stack seems to be large enough to accommodate it. Here is a code snippet:
#include <iostream>
#include <array>
#include <sys/resource.h>
using namespace std;
int main() {
if (struct rlimit rl{1<<28, 1l<<32}; setrlimit(RLIMIT_STACK, &rl))
cout << "Can not set stack size! errno = " << errno << endl;
else
cout << "Stack size: " << rl.rlim_cur/(1<<20) << "MiB to " << rl.rlim_max/(1<<20) << "MiB\n";
array<int8_t, 100'000'000> a;
cout << (int)a[42] << endl;
}
which segfaults when compiled with gcc, but runs fine when compiled with clang 11.0.1 and outputs:
Stack size: 256MiB to 4096MiB
0
EDIT
Clang was eliding allocation of a. Here is a better example:
#include <iostream>
#include <array>
#include <sys/resource.h>
using namespace std;
void f() {
array<int8_t, 100'000'000> a;
cout << (long)&a[0] << endl;
}
int main()
{
if (struct rlimit rl{1<<28, 1l<<32}; setrlimit(RLIMIT_STACK, &rl))
cout << "Can not set stack size! errno = " << errno << endl;
else
cout << "Stack size: " << rl.rlim_cur/(1<<20) << "MiB to " << rl.rlim_max/(1<<20) << "MiB" << endl;
array<int8_t, 100'000'000> a; // line 21
cout << (long)&a[0] << endl; // line 23
f();
}
which you can find at: https://wandbox.org/permlink/XMaGFMa7heWfI9G8. It runs fine when lines 21 and 23 are commented out, but segfaults otherwise.
Use proc(5) and pmap(1) and strace(1) to understand the limitations of your computer.
array<int8_t, 100'000'000> a;
requires about 100Mbytes of space on call stack, which is generally limited to a few megabytes (perhaps even by your Linux kernel, but I am not sure)
Try also cat /proc/$$/limits in your terminal. On mine I am getting
Limit Soft Limit Hard Limit Units
Max cpu time unlimited unlimited seconds
Max file size unlimited unlimited bytes
Max data size unlimited unlimited bytes
Max stack size 8388608 unlimited bytes
The difference of behavior between compilers might be attributed to various optimizations (e.g. permitted by some C++ standard like n4849). A clever enough compiler is allowed to use just a few words for a inside your function f (e.g. because it would figure out, maybe with some abstract interpretation techniques, that locations a[1024] ... a[99999999] are useless).
If you compile with a recent GCC (e.g. GCC 10), you could invoke it as g++ -O -Wall -Wextra -fanalyzer -Wstack-usage=2048 to get useful warnings. See also this draft report funded by CHARIOT & DECODER projects.
In practice, use dynamic allocation for huge data (e.g. placement new with mmap(2) and smart pointers)
For a real application, consider writing your GCC plugin to get ad-hoc warnings.
Or at least compile your source code foo.cc with g++ -O2 -fverbose-asm -S foo.cc and look inside the generated foo.s and repeat with clang++ : the generated assembler files are different.
I have small piece of code for std::for_each_n loop. I tried running it on inbuilt Coliru compiler GCC C++17 using following command :
g++ -std=c++1z -O2 -Wall -pedantic -pthread main.cpp && ./a.out
But compiler give an error that " 'for_each_n' is not a member of 'std' ".
My code is bellow which is copied from cppreference.
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> ns{1, 2, 3, 4, 5};
for (auto n: ns) std::cout << n << ", ";
std::cout << '\n';
std::for_each_n(ns.begin(), 3, [](auto& n){ n *= 2; });
for (auto n: ns) std::cout << n << ", ";
std::cout << '\n';
}
So, Why I'm getting an error?
There is nothing wrong with your code. The issue is that libstdc++ does not support std::for_each_n until GCC 8 and Clang 8. If we look at the header that defines std::for_each_n, we see it does not exist.
However, if you have access to libc++, their header from the official mirror does implement std::for_each_n.
(Update: the current version of the GCC repository now also does include for_each_n)
I have spent 2 days chasing an issue involving C++ container, std::list, and C-Style structs. Is the following undefined behavior (Note the type for the std::list parameter)?
#include <list>
#include <iostream>
using std::cout;
using std::endl;
struct Point_Struct
{
int x;
int y;
};
typedef struct Point_Struct Point;
int main()
{
std::list<Point> line;
Point p;
p.x = 3;
p.y = 10;
line.push_back(p);
cout << "Size of container: " << line.size() << "\n";
// Here's the issue:
line.pop_back();
// The size should be zero.
cout << "Size of container after pop_back(): " << line.size() << "\n";
return 0;
}
I ran this on Visual Studio 2017 and I get an exception error, 0xC0000005, (memory access) on the call to pop_back.
The exception is also thrown on any method that changes the ordering of the items in the list, such as assignment and sort.
If I change the type of line to std::list<Point_Struct>, there are no exceptions thrown.
Note: The issue was found in a larger program. The code above illustrates the root cause of the issue: std::list<typedef struct> vs. std::list<struct>
Note: The exception is thrown in VS2017 debug mode but not in release mode.
Sorry, but multiple questions follow:
Is there anything in standard C++ (11 or later) declaring undefined
behavior for using a typedef instead of a struct as the template
parameter for std::list?
Would this be a Visual Studio bug?
I haven't tried on G++ or other compilers.
Edit 1: VS2017 version info
Microsoft Visual Studio Professional 2017
Version 15.9.14
Installed product: Visual C++ 2017 - 00369-60000-00001-AA071
Compilation Info
Configuration: Debug
Platform: Win32
Warning Level: Level3 (/W3)
Optimization: Disabled (/Od)
Enable C++ Exception: Yes (/EHsc)
Basic Runtime Checks: Both (/RTC1)
Disable Language Extensions: No
Conformance mode: No
Platform
Platform: Windows 7
I compiled and ran your code with g++ 11 in Eclipse (Ubuntu 18) and it worked perfectly,
Output:
Size of container: 1
Size of container after pop_back(): 0
Have you tried/is it possible to swap typedef for using? This might fix it:
#include <list>
#include <iostream>
using std::cout;
using std::endl;
struct Point_Struct
{
int x;
int y;
};
using Point = Point_Struct;
int main()
{
std::list<Point> line;
Point p;
p.x = 3;
p.y = 10;
line.push_back(p);
cout << "Size of container: " << line.size() << "\n";
// Here's the issue:
line.pop_back();
// The size should be zero.
cout << "Size of container after pop_back(): " << line.size() << "\n";
return 0;
}
I'm trying to learn about vectors in C++, but just trying to declare one throws a runtime error in NetBeans.
Error: Run failed (exit value -1, 073, 741, 511, total time 51 ms)
PS: The code works perfectly in Eclipse.
#include <iostream>
#include <vector>
using namespace std;
int main() {
// create a vector to store int
vector<int> vec;
int i;
// display the original size of vec
cout << "vector size = " << vec.size() << endl;
// push 5 values into the vector
for (i = 0; i < 5; i++) {
vec.push_back(i);
}
// display extended size of vec
cout << "extended vector size = " << vec.size() << endl;
// access 5 values from the vector
for (i = 0; i < 5; i++) {
cout << "value of vec [" << i << "] = " << vec[i] << endl;
}
// use iterator to access the values
vector<int>::iterator v = vec.begin();
while (v != vec.end()) {
cout << "value of v = " << *v << endl;
v++;
}
return 0;
}
I have tested on my system (latest GCC and NB dev build) and it works without any problem. The desired output is shown. It also runs fine from command line.
Therefore I assume it's more a configuration or system related problem. But without any further informations it's impossible to find the root cause.
More information please:
What OS / Environment are you using?
What Compiler (and versions) do you have?
What version of Netbeans do you use?
Do other project's work?
Here's some first aid you can try:
Create a new C++ Project (C++ Application). It already includes a blank main() function. Run this and check if there's still an error
Create a simple .cpp file and build it from command line (don't involve any IDE). Does it work this way?
Build and your source file without IDE. From Commandline: g++ <your filename>.cpp
Review your compiler settings (Tools -> Options -> C/C++ at Build Tools). Especially use the Version button and check if everything is right.
Windows only: Make sure you have the correct make executable selected in the compiler settings
Have a look at the IDE's log (View -> IDE Log). Are there any problems mentioned?
Run in Debug without any breakpoint. This is going to stop the execution on any runtime error.
This question already has answers here:
Undefined behavior and sequence points
(5 answers)
Closed 5 years ago.
I am running into a problem which has thrown me for a loop (no pun intended). I was trying to illustrate how overloaded operators can enhance the readability of code quite a bit. In order to do so, I wrote a simple class called 'cow' (no special meaning). When I compile the code on a Mac, it compiles cleanly and executes as expected.
The exact same code compiled on a Linux box (Ubuntu) also compiles cleanly, but executed with an incorrect result.
Somewhere, I must be missing something obvious, but I'm not seeing it.
Here is the code:
#include <iostream>
#include <sstream>
using namespace std;
class cow {
public:
cow();
cow(int i);
int add(int a);
int add(string str);
int get() const;
private:
int i;
};
cow::cow() {
i = 0;
}
cow::cow(int j) {
i = j;
}
int cow::add(string str) {
stringstream s;
int num;
s << str;
s >> num;
return i += num;
}
int cow::add(int a) {
return i += a;
}
int cow::get() const {
return i;
}
int main() {
cow i(15);
cout << i.get() << " : " << i.add(15) << " : " << i.add("-15.0");
return 0;
}
Compiling (g++ -Wall -o cow cow.cpp) yields no warnings and no errors and creates an executable.
Executing the program on the Linux box yields:
$ ./cow
15 : 15 : 0
Executing the program on a Mac yields:
$ ./cow
15 : 30 : 15
The C++ compiler on the Mac is:
$ g++ --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 9.0.0 (clang-900.0.38)
Target: x86_64-apple-darwin16.7.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
The C++ compiler on the Linux box is:
$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.5) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Any suggestions as to what is causing this behavior is appreciated, as are ways to fix it on the Linux box!
Thanks,
Kees
You're getting an undefined behavior because you change the state of the instance several times within one expression. By the C++ standard, your calls to i in this line:
cout << i.get() << " : " << i.add(15) << " : " << i.add("-15.0");
could be performed in any order.
It is just your luck the Mac's compiler performs the calls left to right as you expect.
To get the reliable result you should evaluate those calls sequentially, like:
auto a1 = i.get();
auto a2 = i.add(15);
auto a3 = i.add("-15.0);
cout << a1 << " : " << a2 << " : " << a3;
You're running into undefined behaviour in this line:
cout << i.get() << " : " << i.add(15) << " : " << i.add("-15.0");
It's up to the compiler which order it evaluates i.get (), i.add(15) and i.add("-15.0") - it's not normally a problem unless evaluating one of them would change the output of another of them (which is the case here - i changes).
As you're using different compilers (g++ on Linux, clang on Mac), each is evaluating in different orders.