开发者

What is the maximum string length (or size) that I can pass to function?

开发者 https://www.devze.com 2023-01-27 15:57 出处:网络
I have the following function: int Foo(string sentence); I wa开发者_如何学JAVAnt to know what is the maximum string length I could pass?

I have the following function:

int Foo(string sentence);

I wa开发者_如何学JAVAnt to know what is the maximum string length I could pass? I think it should depend on the stack size allocated to the function as this string will be copied to the stack, is that true? or it depends on string::max_size value? I'm using C++ under VS2010, windows7

EDIT. I need to have a copy as the function modifies the string contents.


The std::string object will be copied onto the stack, but the string body will not - it will be allocated on heap. The actual limitation will depend on the system and program memory usage and can be something like from ten million to one billion charactes on a 32-bit system.


It does not have anything to do with stack size - the string contents are assigned on the heap. So it depends either on string::max_size or how much RAM/virtual memory you have available in your computer.


You can check std::string's max_size() member function.

EDIT

If your standard library implementation doesn't implement Copy On Write optimization, you should pass big strings by const reference. This is true also if you want to be independent from the STL.


It's much more likely that the maximum string length will be determined by the constraints of your system than the theoretical maximum value returned by max_size. max_size on Windows 32-bit is 4 GB, but you will never be able to construct a string that size in the real world on a 32-bit Windows box.

The maximum size you can use at any given juncture will vary, and will likely be (after accounting for string's object size) the same as the biggest contiguous heap allocation that's possible at that instant. This is affected by machine config (how much RAM, how much kernel reserved space, how many other programs and their memory profile). If you then try to do anything else that requires heap memory, you will get exceptions of one type or another. You are better off not getting near to this scenario in the first place.


It will never be more than string::max_size, as that returns the maximum length the implementation supports.

If it also depends on very runtime-dependent things like stack sizes, you probably won't be able to find out.

Needless to say, it's best to pass (long) strings as constant references, to avoid any copying.


It can't be more than max_size() which is implementation dependant.

However best practice would be to pass a reference to it.

int Foo(string& sentence);
0

精彩评论

暂无评论...
验证码 换一张
取 消