473,396 Members | 2,011 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

How to use maximum size of size_t type ?

Hi:

I am a bit new to C programming and am trying to
write a wrapper around malloc. Since malloc takes
size_t as it's parameter, I want to be able to
see if my function recieved an argument less than
or equal to the max size_t type.

So:

//my wrapper function mallocstr
char * mallocstr(size_t num)
{
//TEST
if (CODE HERE TO TEST FOR num <= max size of size_t) {
printf("some debug error message\n");
return NULL;
}
//END TEST
return (char *) malloc(num);
}
Now, ignore the fact that malloc will return NULL if
unsucessful and I may not need the test. If I _do_
want to structure my code in the above fashion, is there
any _way_ to do it ?

I.E., replace the "CODE HERE..." line with some
test that can tell me with my argument was less than
of equal to the max size of the size_t type.

I am on a gcc system and would like to do this portably.
As far as I can tell, there is no gcc defined macro
or any value in limit.h that tells me the max size of
size_t.

Maybe I am missing something, but this appears tougher
than it should be.

Best regards,

--j
Nov 14 '05 #1
11 19435
javadesigner wrote:

Hi:

I am a bit new to C programming and am trying to
write a wrapper around malloc. Since malloc takes
size_t as it's parameter, I want to be able to
see if my function recieved an argument less than
or equal to the max size_t type.

So:

//my wrapper function mallocstr
char * mallocstr(size_t num)
{
//TEST
if (CODE HERE TO TEST FOR num <= max size of size_t) {
printf("some debug error message\n");
return NULL;
}
//END TEST
return (char *) malloc(num);
}

Now, ignore the fact that malloc will return NULL if
unsucessful and I may not need the test. If I _do_
want to structure my code in the above fashion, is there
any _way_ to do it ?

I.E., replace the "CODE HERE..." line with some
test that can tell me with my argument was less than
of equal to the max size of the size_t type.

I am on a gcc system and would like to do this portably.
As far as I can tell, there is no gcc defined macro
or any value in limit.h that tells me the max size of
size_t.

Maybe I am missing something, but this appears tougher
than it should be.


It's pointless.
Any value that you can test within the function,
will be within the range of size_t.
The largest value that will fit in a size_t object,
is ((size_t)-1).

There's a SIZE_MAX macro in C99.

--
pete
Nov 14 '05 #2
Greetings.

In article <bu***********@netnews.upenn.edu>, javadesigner wrote:
I am on a gcc system and would like to do this portably.
As far as I can tell, there is no gcc defined macro
or any value in limit.h that tells me the max size of
size_t.

Maybe I am missing something, but this appears tougher
than it should be.


C99 (and possibly earlier standards; I don't remember) define the SIZE_MAX
macro. It's supported by recent versions of GCC.

A portable fallback is to use the expression (size_t)(-1).

Regards,
Tristan

--
_
_V.-o Tristan Miller [en,(fr,de,ia)] >< Space is limited
/ |`-' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-= <> In a haiku, so it's hard
(7_\\ http://www.nothingisreal.com/ >< To finish what you
Nov 14 '05 #3
javadesigner <re******************@yahoo.com> wrote:
I am a bit new to C programming and am trying to
write a wrapper around malloc. Since malloc takes
size_t as it's parameter, I want to be able to
see if my function recieved an argument less than
or equal to the max size_t type.
Erm. If your function takes a size_t argument...
//my wrapper function mallocstr
char * mallocstr(size_t num)
....which it does, then there's no way you're ever going to get an
argument that does _not_ fit in a size_t. Even if someone tries to pass
a larger number to your function, it's going to be modulated down to
size before being passed to mallocstr(). If size_t could be signed, too
large arguments would invoke I-DB, but it's required to be unsigned, so
it is always going to be passed to you modulo SIZE_MAX.
return (char *) malloc(num);
There is no reason to cast malloc(), btw, unless you have forgotten to
#include <stdlib.h>. malloc() returns a void *, which is useful exactly
because it can hold all kinds of pointers and doesn't need casts.
Now, ignore the fact that malloc will return NULL if
unsucessful and I may not need the test. If I _do_
want to structure my code in the above fashion, is there
any _way_ to do it ?
Partially. Instead of a size_t, take a uintmax_t and check whether your
parameter is <=SIZE_MAX. Since neither of those exists in C89, you'll
have to make do with unsigned long ans (size_t)-1 if you don't have C99.
This means your function doesn't take the same kind of argument as
malloc(), however.
Moreover, size_t could even be larger than unsigned long (at least, I
can't find a reason why it couldn't), which would mean that mallocstr()
would actually have a smaller range than malloc(). In C99, with
uintmax_t, that would not be a problem.
As far as I can tell, there is no gcc defined macro
or any value in limit.h that tells me the max size of
size_t.


Not if you have a pre-C99 version of gcc, but since size_t is guaranteed
to be unsigned and values assigned to unsigned types are changed modulo
the size of the type if they're out of range, (size_t)-1 will give you
the maximum value of a size_t. It's still not much use if you take a
size_t in the first place, of course.

Richard
Nov 14 '05 #4
In <40***************@news.individual.net> rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
Moreover, size_t could even be larger than unsigned long (at least, I
can't find a reason why it couldn't), which would mean that mallocstr()
would actually have a smaller range than malloc().


Nope, this is not possible in C89, which doesn't have extended integer
types. A conforming C89 implementation may define __longlong as an
extension, but it doesn't count as an integer type from C89's point of
view.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #5
Hi:

Firstly, thanks to all who replied. I am amazed
at the high signal/noise ratio in this group (unlike
other comp.lang.* groups).

So the whole idea of mallocstr was to make sure
my string allocation had the "1 more" char for
the null (\0) terminator. I know I'll forget to
mallon (len + 1) so why not have a mallocstr
that does that for me automatically ?

I reason, I needed to check to see if the supplied
argument was len < max size of size_t was to ensure
enough space for len + 1

So

#define DBG_FLOW 1

#define pfcall(argstr, args) \
printf("--> %s(" argstr ") [%s, %d]\n", __func__, (args), __FILE__,
__LINE__)

#define fpfcall(fd, argstr, args) \
fprintf(fd, "%s(" argstr ") [%s, %d]\n", __func__, (args), __FILE__,
__LINE__)

typedef char * string; //personal preference

string mallocstr(size_t num_chars)
{
#ifdef DBG_FLOW
pfcall("%zu", num_chars);
#endif;

if (num_chars == (size_t) -1) //or num_chars == SIZE_MAX
{
fpfcall(stderr,
"Cannot allocate chars since %zu == max size_t and no space left for one
more \\n character\n",
num_chars);
return NULL;
}
return (string) malloc(num_chars + 1);
}

Comments ? Again, I am new to C so please _do_ flame me
if the above code/debug macros suck.

Best regards,

--j
Nov 14 '05 #6
in comp.lang.c i read:
there's no way you're ever going to get an argument that does _not_ fit in
a size_t. Even if someone tries to pass a larger number to your function,
it's going to be [...] modulo SIZE_MAX.
only if SIZE_MAX is the same as the maximum value of the underlying
unsigned type. that is almost certain to be the case except in a
pathological implementation, e.g., where size_t is an alias for unsigned
long and ULONG_MAX is 4294967295 but SIZE_MAX is 2147483647.
Moreover, size_t could even be larger than unsigned long (at least, I
can't find a reason why it couldn't),


size_t must be an alias for an unsigned integral type, and pre-c99 there
are no extended types so at most it's an unsigned long in those compilers.

--
a signature
Nov 14 '05 #7
javadesigner wrote:

Hi:

Firstly, thanks to all who replied. I am amazed
at the high signal/noise ratio in this group (unlike
other comp.lang.* groups).

So the whole idea of mallocstr was to make sure
my string allocation had the "1 more" char for
the null (\0) terminator. I know I'll forget to
mallon (len + 1) so why not have a mallocstr
that does that for me automatically ?

I reason, I needed to check to see if the supplied
argument was len < max size of size_t was to ensure
enough space for len + 1

So

#define DBG_FLOW 1

#define pfcall(argstr, args) \
printf("--> %s(" argstr ") [%s, %d]\n", __func__, (args), __FILE__,
__LINE__)

#define fpfcall(fd, argstr, args) \
fprintf(fd, "%s(" argstr ") [%s, %d]\n", __func__, (args), __FILE__,
__LINE__)

typedef char * string; //personal preference

string mallocstr(size_t num_chars)
{
#ifdef DBG_FLOW
pfcall("%zu", num_chars);
#endif;

if (num_chars == (size_t) -1) //or num_chars == SIZE_MAX
{
fpfcall(stderr,
"Cannot allocate chars since %zu == max size_t and no space left for one
more \\n character\n",
num_chars);
return NULL;
}
return (string) malloc(num_chars + 1);
}

Comments ? Again, I am new to C so please _do_ flame me
if the above code/debug macros suck.


The only way I can imagine that a string's null terminating
character could be more that ((size_t)-1) away from
the head of the string,
is if the string spans at least two different objects.
As far as I know, string spanning across two unrelated objects,
is merely an accidental condition that can be checked for,
rather than something that you can code deliberately.

If your string is contained within an object, like every
useful string in real code is, then size_t is big enough.

--
pete
Nov 14 '05 #8
> The only way I can imagine that a string's null terminating
character could be more that ((size_t)-1) away from
the head of the string,
is if the string spans at least two different objects.


As a newbie, I have no idea what you mean by "object". I am
presuming you don't mean C++ objects of course, so what does
'object' refer to in the context of plain old C ?

Best regards,

--j

Nov 14 '05 #9
javadesigner wrote:
The only way I can imagine that a string's null terminating
character could be more that ((size_t)-1) away from
the head of the string,
is if the string spans at least two different objects.


As a newbie, I have no idea what you mean by "object". I am
presuming you don't mean C++ objects of course, so what does
'object' refer to in the context of plain old C ?


All variables are objects. Function parameters are objects.
When a string literal "like this one" is used to initialize
a string pointer, the string literal is paradoxically, the
name of an anonymous object, that object being an array of char.
Multiple occurances of identical string literals in code,
may refer to the same object, or may each refer to a different one.

* Object --- a region of data storage in the execution environment,
the contents of which can represent values. Except for bit-fields,
objects are composed of contiguous sequences of one or more bytes,
the number, order, and encoding of which are either explicitly
specified or implementation-defined.

--
pete
Nov 14 '05 #10
pete wrote:
When a string literal "like this one" is used to initialize
a string pointer, the string literal is paradoxically, the
name of an anonymous object, that object being an array of char.


When a string literal "like this one" is used to initialize
an array of char, then it is just an initializer list and doesn't
imply that there is any other array besides the one being initialized.

When it is the operand of sizeof, it's an array.
sizeof"this" equals 5, (4 characters plus 1 more null character).

--
pete
Nov 14 '05 #11
In <m1*************@usa.net> those who know me have no need of my name <no****************@usa.net> writes:
in comp.lang.c i read:
there's no way you're ever going to get an argument that does _not_ fit in
a size_t. Even if someone tries to pass a larger number to your function,
it's going to be [...] modulo SIZE_MAX.


only if SIZE_MAX is the same as the maximum value of the underlying
unsigned type. that is almost certain to be the case except in a
pathological implementation, e.g., where size_t is an alias for unsigned
long and ULONG_MAX is 4294967295 but SIZE_MAX is 2147483647.


Such an implementation would be non-conforming. SIZE_MAX is a property
of the type aliased by size_t, so, if size_t is an alias for unsigned
long, SIZE_MAX *must* be the same as ULONG_MAX. There is no way to have
(size_t)-1 != SIZE_MAX in a conforming implementation.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Till Crueger | last post by:
Hi, I have to implement some simple sorting algorithm. I am NOT asking for you to do my homework, but my question is rather on how to store the integers. I recall reading once in here that there...
8
by: codefixer | last post by:
Hi, I was wondering what factors will influence the maximum buffer sizes for source and destination for memcpy(). Is their any limit to the sizeof the buffer(hardware restricting it ?) OR any...
2
by: Kums | last post by:
What is the maximum permissible size of a database? Is there any limitation. What is the maximum # of tablespace's allowed in a database? Thanks for your response.
5
by: Evangelista Sami | last post by:
hello is there a maximum size that can be allocated by a malloc call? is this defined by the standard? thanks Sami Evangelista
19
by: Jerry | last post by:
I am wondering what is the maximum size of memory that malloc() could handle. Is there any limitation on that? Where am I supposed to get this kind of information? Thank you everybody.
15
by: uremae | last post by:
I tried to open some large files in my computer. (ram 512MB) 1. is there limitation of file size FOPEN? 2. if I have a file that is larger than the maximum size, how can I open the file?
11
by: mast2as | last post by:
This question has been posted to this forum before and I read the thread but found that the answers were perhaps imcomplete, so I am trying again. Whenever I am creating objects I would like to...
30
by: Angel Tsankov | last post by:
Hello! Does the C++ standard define what happens when the size argument of void* operator new(size_t size) cannot represent the total number of bytes to be allocated? For example: struct S {...
36
by: James Harris | last post by:
Initial issue: read in an arbitrary-length piece of text. Perceived issue: handle variable-length data The code below is a suggestion for implementing a variable length buffer that could be used...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.