简体   繁体   中英

strlen to return size_t?

In C:
My string length function is returning a size_t value?

Why is it not returning a integer which is conventional? And one more thing I noticed was that when I was trying concatenate this string with another string I received a bus error when I ran the program.

Context: I was kind of playing with gmp library and converting big numbers to strings and I end up with the above situation.

What kind of a string is that? Is my operating system playing a role in this issue? I use a MAC, 64-bit OS.

Edited: The error message I received was:

: warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘size_t’

Thanks!

@all: Thanks for the answers but I thought I will put the bus error as another question because it seems to be a different issue.

The problem is int might be not wide enough to store the whole range of possible length values. For example on 64-bit you can have a string longer than 4 gigabytes and if int is 32 bit you can't possibly return length of such a long string via an int variable.

POSIX strlen() does return size_t .

As to what's caused the bus error, it's impossible to say without seeing the code and knowing more details about the exact nature of your changes. One possibility is that you've caused a buffer overrun or did something with a NULL pointer you shouldn't have done.

strlen() always returned size_t ... and the POSIX standard also says that.

I guess the reason is that int has sign and the capacity of even an unsigned int might not be enough for holding size of an element (say if you have a 32bit int on x86-64 with 16GB RAM) ... the example is extreme, but possible.

strlen() returns a size_t since at least ISO C90 -- I just checked in my copy. And this standard should have no technical difference with ANSI C89.

There was a change of convention ( size_t wasn't in K&R C), but it was a long time ago.

要解决您的警告(实际上是一个错误-您通过将错误的类型传递给printf来调用未定义的行为),您应该使用%zu而不是%d来打印size_t值。

There is a very simple and logical reason for all of the functions from the standard library to work with size_t when it comes to lengths of memory blocks - the built-in sizeof operator yields a size_t result as well.

Moreover, size_t is unsigned, of a particular size, tied to the architecture and is semantically different than just a generic int which is meant for storing any number from the count of trees around your office to your SO reputation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM