473,289 Members | 1,743 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,289 software developers and data experts.

sizeof

Hi,
How can we write a function, which functionality is similar to sizeof
function
any one send me source code
Reddy

Jun 18 '06 #1
90 8226
pn*********@gmail.com said:
Hi,
How can we write a function, which functionality is similar to sizeof
function


We can't, because sizeof is not a function. (And there's a good reason why
it's not a function.)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 18 '06 #2
Richard Heathfield wrote:
pn*********@gmail.com said:
Hi,
How can we write a function, which functionality is similar to sizeof
function


We can't, because sizeof is not a function. (And there's a good reason why
it's not a function.


Can you tell us that reason, Richard?

Regards,
Madhav.

Jun 18 '06 #3
Madhav said:
Richard Heathfield wrote:
pn*********@gmail.com said:
> Hi,
> How can we write a function, which functionality is similar to sizeof
> function


We can't, because sizeof is not a function. (And there's a good reason
why it's not a function.


Can you tell us that reason, Richard?


Spend a little time trying to write such a function, and you'll discover it
for yourself quickly enough. Hint: what type should its parameter be?

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 18 '06 #4
pn*********@gmail.com wrote:
Hi,
How can we write a function, which functionality is similar to sizeof
function
any one send me source code


the problem is that the result of sizeof() is interpolated at compile
time. Can any function do it that way! :-)

Xicheng

Jun 18 '06 #5

"Xicheng Jia" <xi*****@gmail.com> wrote in message
pn*********@gmail.com wrote:
Hi,
How can we write a function, which functionality is similar to sizeof
function
any one send me source code


the problem is that the result of sizeof() is interpolated at compile
time. Can any function do it that way! :-)

A compiler is permitted to inline functions, and then to simplify code. A
really good compiler might simplify constructs like acos(0) to produce half
PI, but this is rare.
--
Buy my book 12 Common Atheist Arguments (refuted)
$1.25 download or $7.20 paper, available www.lulu.com/bgy1mm
Jun 18 '06 #6
Xicheng Jia posted:
Can any function do it that way! :-)

A macro function perhaps:
#define SizeOf(Type) \
( \
(const char*)128 - \
\
(const char*)( (const Type*)128 - 1 ) \
)
--

Frederick Gotham
Jun 18 '06 #7

Richard Heathfield wrote:
Spend a little time trying to write such a function, and you'll discover it
for yourself quickly enough. Hint: what type should its parameter be?


I think it is because we need C language to tell us the sizes of
various types and objects by sizeof. It's the purpose of sizeof itself
and why it is called the name operator. We have no alternative choice.

lovecreatesbeauty

Jun 18 '06 #8
Frederick Gotham schrieb:
Xicheng Jia posted:
Can any function do it that way! :-)

A macro function perhaps:
#define SizeOf(Type) \
( \
(const char*)128 - \
\
(const char*)( (const Type*)128 - 1 ) \
)


Undefined behaviour - your pointer most likely does not point to any
valid object. And even if it does on certain implementations, it makes
no sense in c.l.c as conversion from integer to pointer types is
implementation defined and thus not portable.

--
Marc Thrun
http://www.tekwarrior.de/
Jun 18 '06 #9
Marc Thrun posted:
Frederick Gotham schrieb:
Xicheng Jia posted:
Can any function do it that way! :-)

A macro function perhaps:
#define SizeOf(Type) \
( \
(const char*)128 - \
\
(const char*)( (const Type*)128 - 1 ) \
)


Undefined behaviour - your pointer most likely does not point to any
valid object. And even if it does on certain implementations, it makes
no sense in c.l.c as conversion from integer to pointer types is
implementation defined and thus not portable.

Yes I'm aware of that.

This thread isn't about anything serious; it's more of a little mind game
to see who can write a "sizeof".
--

Frederick Gotham
Jun 18 '06 #10
On 2006-06-18, Xicheng Jia <xi*****@gmail.com> wrote:
pn*********@gmail.com wrote:
Hi,
How can we write a function, which functionality is similar to sizeof
function
any one send me source code


the problem is that the result of sizeof() is interpolated at compile
time. Can any function do it that way! :-)


Yes, any standard function could do it that way; the compiler has control
over all the libraries included with it. Not only that, but with C99 VLA's,
sizeof /cannot/ be computer at compile time in some cases.

--
Andrew Poelstra < http://www.wpsoftware.net/blog >
To email me, use "apoelstra" at the above address.
I know that area of town like the back of my head.
Jun 18 '06 #11
ada
Andrew Poelstra <ap*******@localhost.localdomain> writes:
On 2006-06-18, Xicheng Jia <xi*****@gmail.com> wrote:
pn*********@gmail.com wrote:
Hi,
How can we write a function, which functionality is similar to sizeof
function
any one send me source code
the problem is that the result of sizeof() is interpolated at compile
time. Can any function do it that way! :-)


Yes, any standard function could do it that way; the compiler has control
over all the libraries included with it. Not only that, but with C99 VLA's,
sizeof /cannot/ be computer at compile time in some cases.

Why?
--
Andrew Poelstra < http://www.wpsoftware.net/blog >
To email me, use "apoelstra" at the above address.
I know that area of town like the back of my head.

Jun 18 '06 #12
Andrew Poelstra wrote:
On 2006-06-18, Xicheng Jia <xi*****@gmail.com> wrote:
pn*********@gmail.com wrote:
Hi,
How can we write a function, which functionality is similar to sizeof
function
any one send me source code


the problem is that the result of sizeof() is interpolated at compile
time. Can any function do it that way! :-)


Yes, any standard function could do it that way; the compiler has control
over all the libraries included with it. Not only that, but with C99 VLA's,
sizeof /cannot/ be computer at compile time in some cases.


Sorry, I should have said that the operand of sizeof() is interpolated
at compile-time. so i++ in sizeof(i++) does not increment i and the
following code prints 'i = 1' instead of 'i = 2'..

#include<stdio.h>
int main()
{
int i = 1, sz;
sz = sizeof(i++);
printf("i = %d\n", i);
return 0;
}

In ISO C, Macro is a different thing from function. and I am not sure
if inline function can do things like sizeof() does though . any hints
about this, thanks..:)

Xicheng

Jun 18 '06 #13
pn*********@gmail.com writes:
How can we write a function, which functionality is similar to sizeof
function
Why would you want to do that?
any one send me source code


Nope.

The only plausible reason to do something like this is as a homework
assignment (though it's a particularly bad one). If this is the case
here, we're certainly not going to do your homework for you.

If you have some other reason, tell us what it is. Tell us what
you're *really* trying to accomplish, and we might be able to help you
find a better solution. (Based on your question, a better solution is
obvious: use the sizeof operator, that's what it's for.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jun 18 '06 #14
ada said:
Andrew Poelstra <ap*******@localhost.localdomain> writes:


<snip>
Not only that, but with C99
VLA's, sizeof /cannot/ be computer at compile time in some cases.

Why?


Here's one reason:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
puts("How many array elements would you like?");
char buf[32];
if(fgets(buf, sizeof buf, stdin) != NULL)
{
unsigned long n = strtoul(buf, NULL, 10);
if(n > 0)
{
int arr[n];
/* ... */

There is simply no way that the compiler can know at compile time how many
elements the user will ask for at run time.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 18 '06 #15
Madhav wrote:

Richard Heathfield wrote:
pn*********@gmail.com said:
Hi,
How can we write a function,
which functionality is similar to sizeof function


We can't, because sizeof is not a function.
(And there's a good reason why
it's not a function.


Can you tell us that reason, Richard?


The result of the sizeof operator must be a constant expression,
whenever the operand isn't a variable length array.

--
pete
Jun 19 '06 #16
Richard Heathfield wrote:
There is simply no way that the compiler can know at compile time how many
elements the user will ask for at run time.


Is following the inconsistent between the standard and implementations?

#include <stdio.h>

int main(void)
{
int len = 10;
char a[len];

switch (sizeof a)
{
case 10:
printf("%s", "10 elements");
break;
default:
printf("<unknow>");
break;
}

fflush(stdout);

return 0;
}

$ gcc test.c
$ ./a.out
10 elements$
$

lovecreatesbeauty

/*quoting begins*/
6.6 Constant expressions
2 A constant expression can be evaluated during translation rather than
runtime, <snip>

6.8.4.2 The switch statement
3 The expression of each case label shall be an integer constant
expression <snip>
/*quoting ends*/

Jun 19 '06 #17
In article <df********************@bt.com>,
Richard Heathfield <in*****@invalid.invalid> wrote:
Madhav said:
Richard Heathfield wrote:
We can't, because sizeof is not a function. (And there's a good reason
why it's not a function.


Can you tell us that reason, Richard?


Spend a little time trying to write such a function, and you'll discover it
for yourself quickly enough. Hint: what type should its parameter be?


--------
template<class T>
std::size_t my_sizeof(const T&)
{
assert(HAS_FLAT_MEMORY_SPACE_AND_UNCHECKED_POINTER _ARITHMETIC);
T* x=0;
T* y=x+1;
return static_cast<std::size_t>(
static_cast<char*>(y)-static_cast<char*>(x));
}
--------

If you'll excuse me while I go find a pointy stick to poke my sigmonster
with, I'll be right back...
dave

--
Dave Vandervies dj******@csclub.uwaterloo.ca
Suggesting to comp.lang.c that they use C++ compilers and inline assembly is
like suggesting to an American that you can get nice and warm by burning an
American flag. --Richard Heathfield in comp.lang.c
Jun 19 '06 #18

Dave Vandervies wrote:
template<class T>
std::size_t my_sizeof(const T&)


C language has no template, namespace, :: and function overloading
things. Even you can't find any word same as "template", "namespace" or
"overload" in the standard document.

lovecreatesbeauty

Jun 19 '06 #19
In article <11*********************@g10g2000cwb.googlegroups. com>,
lovecreatesbeauty <lo***************@gmail.com> wrote:

Dave Vandervies wrote:
template<class T>
std::size_t my_sizeof(const T&)
C language has no template, namespace, :: and function overloading
things. Even you can't find any word same as "template", "namespace" or
"overload" in the standard document.


If you hadn't stopped reading there, and had been willing and able to
engage your brain while continuing to read, you would probably have
realized that I was aware of that.

(It also subtly fails to meet RH's spec, while providing enough
information to allow the OP to write (non-function) code to meet his
original spec without doing his homework for him. Which, really, is
all anybody could ask for in a homework thread.)
dave
(procrastinating doing homework of my own)

--
Dave Vandervies dj******@csclub.uwaterloo.caYup. Now, how does one fit this into a four-line .sig?

"People are stupid."
--Arvid Grotting and Mike Sphar in the Scary Devil Monastery
Jun 19 '06 #20
"lovecreatesbeauty" <lo***************@gmail.com> writes:
Richard Heathfield wrote:
There is simply no way that the compiler can know at compile time how many
elements the user will ask for at run time.


Is following the inconsistent between the standard and implementations?

#include <stdio.h>

int main(void)
{
int len = 10;
char a[len];

switch (sizeof a)
{
case 10:
printf("%s", "10 elements");
break;
default:
printf("<unknow>");
break;
}

fflush(stdout);

return 0;
}

$ gcc test.c
$ ./a.out
10 elements$
$

lovecreatesbeauty

/*quoting begins*/
6.6 Constant expressions
2 A constant expression can be evaluated during translation rather than
runtime, <snip>

6.8.4.2 The switch statement
3 The expression of each case label shall be an integer constant
expression <snip>
/*quoting ends*/


No, there's no inconsistency. The only thing that 6.8.4.2 applies to
in the program is the literal 10 in "case 10:"; that's clearly an
integer constant expression. The expression in parentheses following
the keyword "switch" doesn't need to be constant (the switch statement
wouldn't be very useful if it did).

switch(rand()) {
...
}

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jun 19 '06 #21
On Mon, 19 Jun 2006 02:13:47 +0000, ada <da*******@gmail.com> wrote:
Andrew Poelstra <ap*******@localhost.localdomain> writes:
On 2006-06-18, Xicheng Jia <xi*****@gmail.com> wrote:
pn*********@gmail.com wrote:
Hi,
How can we write a function, which functionality is similar to sizeof
function
any one send me source code

the problem is that the result of sizeof() is interpolated at compile
time. Can any function do it that way! :-)


Yes, any standard function could do it that way; the compiler has control
over all the libraries included with it. Not only that, but with C99 VLA's,
sizeof /cannot/ be computer at compile time in some cases.

Why?


In the code fragment
int x[5];
int y;
y = sizeof x;
The right had side is a compile time constant that the compiler could
evaluate at compile time and replace with 20 (for a system with four
byte int).

In the C99 fragment
int y;
scanf("%d", &y);
int x[y];
y = sizeof x;
The right hand side cannot be evaluated until after the user enters a
value for y.
Remove del for email
Jun 19 '06 #22
lovecreatesbeauty said:
Dave Vandervies wrote:
template<class T>
std::size_t my_sizeof(const T&)


C language has no template, namespace, :: and function overloading
things. Even you can't find any word same as "template", "namespace" or
"overload" in the standard document.


Dear Granny

To begin, you'll need to find an egg. A large chicken's egg would be good,
or any other egg of about the same size. You should be able to buy a box of
half a dozen eggs from that supermarket you've been using for the last
fifty years or so. Just ask the assistant.

You need to work out which is the smaller end, and which the larger end. The
easiest way to do this is to place the egg carefully on a table-top, and
spin it. The smaller end, being further from the centre, will move round a
lot quicker. Mark the smaller end with a little pencil mark. That's the end
you'll be sucking from.

Now you'll need to make two holes in the egg. The first hole is at the
sucking end, and that's for you to suck through. The second hole is at the
big end, and that's to let air flow into the shell, replacing everything
you suck (otherwise, even if you were able to suck anything out, which is
unlikely, the shell would then be crushed by air pressure).

Use a sewing needle to make a tiny hole in each end of the egg. Then enlarge
the hole at the sucking end until it's about a quarter of an inch wide. The
hole at the other end need only be about a twelfth of an inch wide. Make
sure the holes are at the very ends of the egg, and be careful not to break
the egg while you're doing this.

Lift the egg to your lips, making sure you have the proper end (the small
end) facing you. Make sure your lips are preventing the egg's shell from
going into your mouth. Tip the egg slightly upwards at the far end, so that
gravity pulls down the eggy stuff to your end.

Pretend the egg is a straw. Suck through it. Swallow the eggy stuff as it
pours into your mouth, trying hard not to worry about what it tastes like.
Keep sucking it until there's no eggy stuff left in the shell.

If you do this right, you'll get an empty, but intact, egg-shell. As a
reward, you may have a glass of water to help take away the foul taste.

Your loving grandson

Jun 19 '06 #23
Richard Heathfield wrote:
lovecreatesbeauty said:
Dave Vandervies wrote:
template<class T>
std::size_t my_sizeof(const T&)
C language has no template, namespace, :: and function overloading
things. Even you can't find any word same as "template", "namespace" or
"overload" in the standard document.


Dear Granny

<snip> Your loving grandson


Mr. Heathfield, is it relative?

lovecreatesbeauty

Jun 19 '06 #24
Xicheng Jia wrote:
Andrew Poelstra wrote:
On 2006-06-18, Xicheng Jia <xi*****@gmail.com> wrote:
pn*********@gmail.com wrote:
Hi,
How can we write a function, which functionality is similar to sizeof
function
any one send me source code
the problem is that the result of sizeof() is interpolated at compile
time. Can any function do it that way! :-)

Yes, any standard function could do it that way; the compiler has control
over all the libraries included with it. Not only that, but with C99 VLA's,
sizeof /cannot/ be computer at compile time in some cases.


Sorry, I should have said that the operand of sizeof() is interpolated
at compile-time.


"You keep using that word. I do not think it means what you think it means."

You're probably looking for "evaluated".

S.
Jun 19 '06 #25

"Richard Heathfield" <in*****@invalid.invalid> wrote
Not only that, but with C99
VLA's, sizeof /cannot/ be computer at compile time in some cases.

Why?


Here's one reason:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
puts("How many array elements would you like?");
char buf[32];
if(fgets(buf, sizeof buf, stdin) != NULL)
{
unsigned long n = strtoul(buf, NULL, 10);
if(n > 0)
{
int arr[n];
/* ... */

There is simply no way that the compiler can know at compile time how many
elements the user will ask for at run time.

You mean to say that your compiler won't figure out that
9999999999999999999999999999999 is the maximum the user can enter and
allocate an array accordingly?
--
Buy my book 12 Common Atheist Arguments (refuted)
$1.25 download or $7.20 paper, available www.lulu.com/bgy1mm

Jun 19 '06 #26
On 2006-06-19, Malcolm <re*******@btinternet.com> wrote:

"Richard Heathfield" <in*****@invalid.invalid> wrote
Not only that, but with C99
VLA's, sizeof /cannot/ be computer at compile time in some cases.
Why?


Here's one reason:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
puts("How many array elements would you like?");
char buf[32];
if(fgets(buf, sizeof buf, stdin) != NULL)
{
unsigned long n = strtoul(buf, NULL, 10);
if(n > 0)
{
int arr[n];
/* ... */

There is simply no way that the compiler can know at compile time how many
elements the user will ask for at run time.

You mean to say that your compiler won't figure out that
9,999,999,999,999,999,999,999,999,999,999 is the maximum the user can enter and
allocate an array accordingly?


I've never seen a system with that much memory. Even if it was allocating
an array of char, that's still almost 10 million million million terabytes.

I'll have to assume that you were joking. ;-)

--
Andrew Poelstra < http://www.wpsoftware.net/blog >
To email me, use "apoelstra" at the above address.
I know that area of town like the back of my head.
Jun 20 '06 #27
lovecreatesbeauty wrote:
Richard Heathfield wrote:
lovecreatesbeauty said:
Dave Vandervies wrote:
template<class T>
std::size_t my_sizeof(const T&)
C language has no template, namespace, :: and function overloading
things. Even you can't find any word same as "template", "namespace" or
"overload" in the standard document.

Dear Granny

<snip>
Your loving grandson


Mr. Heathfield, is it relative?

lovecreatesbeauty

So much humour and irony seems to slip by us.

One of the older and time honored bits of advice to youngsters is "Don't
bother telling Granny how to suck eggs." She knows how. She's been doing
it since before she gave birth to your mother.

That Mr. Heathfield knows how (he does!) is interesting. :=)

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Jun 20 '06 #28
Malcolm said:

"Richard Heathfield" <in*****@invalid.invalid> wrote

There is simply no way that the compiler can know at compile time how
many elements the user will ask for at run time.

You mean to say that your compiler won't figure out that
9999999999999999999999999999999 is the maximum the user can enter and
allocate an array accordingly?


If you could store the value of a single bit on a hydrogen atom, and if you
managed to jam the atoms so close together that there were no inter-atomic
gaps (and somehow doing this without impairing your ability to read and
write the bits), 1e32 bytes of storage would require a memory unit 700
metres long, 700 metres wide, and 700 metres tall. For comparison, the
world's tallest building, the Taipei 101 Tower, is a mere 509 metres high.

The volume of this memory unit would be over 340 million cubic metres. For
comparison, the world's largest building (by usable volume), Boeing's
Everett Plant, near Seattle, is a mere 5.64 million cubic metres.

The memory unit would have a mass of 1.33 million tonnes, which is
considerably in excess of the mass of the Palace of the Parliament in
Romania, the world's most massive building.

That's what I call Big Iron.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 20 '06 #29
Richard Heathfield wrote:
Malcolm said:
"Richard Heathfield" <in*****@invalid.invalid> wrote
There is simply no way that the compiler can know at compile time how
many elements the user will ask for at run time.


You mean to say that your compiler won't figure out that
9999999999999999999999999999999 is the maximum the user can enter and
allocate an array accordingly?

If you could store the value of a single bit on a hydrogen atom, and if you
managed to jam the atoms so close together that there were no inter-atomic
gaps (and somehow doing this without impairing your ability to read and
write the bits), 1e32 bytes of storage would require a memory unit 700
metres long, 700 metres wide, and 700 metres tall. For comparison, the
world's tallest building, the Taipei 101 Tower, is a mere 509 metres high.

The volume of this memory unit would be over 340 million cubic metres. For
comparison, the world's largest building (by usable volume), Boeing's
Everett Plant, near Seattle, is a mere 5.64 million cubic metres.

The memory unit would have a mass of 1.33 million tonnes, which is
considerably in excess of the mass of the Palace of the Parliament in
Romania, the world's most massive building.

That's what I call Big Iron.

The fun part would be putting a (very long) match to it.....

--
Ian Collins.
Jun 20 '06 #30
Richard Heathfield <in*****@invalid.invalid> writes:
Malcolm said:
"Richard Heathfield" <in*****@invalid.invalid> wrote
There is simply no way that the compiler can know at compile time how
many elements the user will ask for at run time.

You mean to say that your compiler won't figure out that
9999999999999999999999999999999 is the maximum the user can enter and
allocate an array accordingly?


If you could store the value of a single bit on a hydrogen atom, and if you
managed to jam the atoms so close together that there were no inter-atomic
gaps (and somehow doing this without impairing your ability to read and
write the bits), 1e32 bytes of storage would require a memory unit 700
metres long, 700 metres wide, and 700 metres tall. For comparison, the
world's tallest building, the Taipei 101 Tower, is a mere 509 metres high.

The volume of this memory unit would be over 340 million cubic metres. For
comparison, the world's largest building (by usable volume), Boeing's
Everett Plant, near Seattle, is a mere 5.64 million cubic metres.

The memory unit would have a mass of 1.33 million tonnes, which is
considerably in excess of the mass of the Palace of the Parliament in
Romania, the world's most massive building.

That's what I call Big Iron.


And it still wouldn't help, since in the program (lost in the depths
of followup snippage), the sizeof operator when applied to the VLA
must yield the actual number of bytes requested by the user at run
time.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jun 20 '06 #31
Richard Heathfield wrote:
If you could store the value of a single bit on a hydrogen atom, and if you
managed to jam the atoms so close together that there were no inter-atomic
gaps (and somehow doing this without impairing your ability to read and
write the bits), 1e32 bytes of storage would require a memory unit 700
metres long, 700 metres wide, and 700 metres tall. For comparison, the
world's tallest building, the Taipei 101 Tower, is a mere 509 metres high.

The volume of this memory unit would be over 340 million cubic metres. For
comparison, the world's largest building (by usable volume), Boeing's
Everett Plant, near Seattle, is a mere 5.64 million cubic metres.

The memory unit would have a mass of 1.33 million tonnes, which is
considerably in excess of the mass of the Palace of the Parliament in
Romania, the world's most massive building.

That's what I call Big Iron.


Your chemistry isn't so good, then ...

Recycling used memory might start a flame war.

--
Chris "H to Fe ... no, hang on, H to /H/e" Dollin
"Never ask that question!" Ambassador Kosh, /Babylon 5/

Jun 20 '06 #32
Andrew Poelstra wrote:

On 2006-06-19, Malcolm <re*******@btinternet.com> wrote:

[...]
puts("How many array elements would you like?");
char buf[32];
if(fgets(buf, sizeof buf, stdin) != NULL)
{
unsigned long n = strtoul(buf, NULL, 10);
if(n > 0)
{
int arr[n];
/* ... */

There is simply no way that the compiler can know at compile time
how many elements the user will ask for at run time.

You mean to say that your compiler won't figure out that
9,999,999,999,999,999,999,999,999,999,999 is the maximum the user can
enter and allocate an array accordingly?


I've never seen a system with that much memory. Even if it was allocating
an array of char, that's still almost 10 million million million terabytes.


(BTW, does the Standard say where variable-length arrays are stored?
Can the compiler do the equivalent of malloc/free to handle it?)

I've seen systems which can "allocate" memory without actually using
any memory until something is written to it. As long as you have at
least 103 bits of address space, one could "allocate" that much memory
on such a system, as long as you didn't try to write to all of it.
(Just as I was able to create a billion-byte file on a 1MB floppy,
many years ago.)

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th*************@gmail.com>

Jun 20 '06 #33
Kenneth Brody <ke******@spamcop.net> writes:
[...]
(BTW, does the Standard say where variable-length arrays are stored?
No more than it says where anything is stored. VLAs are like any
other auto objects; they're created at the point of declaration, and
cease to exist at the end of their scope.
Can the compiler do the equivalent of malloc/free to handle it?)
Sure.
I've seen systems which can "allocate" memory without actually using
any memory until something is written to it. As long as you have at
least 103 bits of address space, one could "allocate" that much memory
on such a system, as long as you didn't try to write to all of it.
There's some debate about whether such systems are conforming.
(Just as I was able to create a billion-byte file on a 1MB floppy,
many years ago.)


<OT>Some filesystems optimize long sequences of 0 bytes (which can
have surprising results when you copy a file using a mechanism that
doesn't recognize the optimization).</OT>

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jun 20 '06 #34
Keith Thompson wrote:

Kenneth Brody <ke******@spamcop.net> writes: [...]
I've seen systems which can "allocate" memory without actually using
any memory until something is written to it. As long as you have at
least 103 bits of address space, one could "allocate" that much memory
on such a system, as long as you didn't try to write to all of it.


There's some debate about whether such systems are conforming.


What would be non-conforming about it? (My guess is that, given
this scenario, it's possible that malloc succeeds [ie: returns a
non-NULL value], but the program fails later when it access this
memory and the O/S discovers "oops, there's really not enough
virtual memory available to allocate".)
(Just as I was able to create a billion-byte file on a 1MB floppy,
many years ago.)


<OT>Some filesystems optimize long sequences of 0 bytes (which can
have surprising results when you copy a file using a mechanism that
doesn't recognize the optimization).


In this case, it's "sparse allocation". That is, it allocates space
on the disk for the sector containing the billionth byte of the file
(along with necessary overhead), without allocating physical disk
space for the intervening sectors. Writing intervening bytes, even
if they're all zeros, would have allocated physical space, AFAIK.

I (briefly) considered this for a method of copy protection, by
writing critical data throughout this "billion byte file", which
you couldn't copy via standard copy methods.
</OT>

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th*************@gmail.com>

Jun 20 '06 #35
Kenneth Brody <ke******@spamcop.net> writes:
Keith Thompson wrote:

Kenneth Brody <ke******@spamcop.net> writes:

[...]
> I've seen systems which can "allocate" memory without actually using
> any memory until something is written to it. As long as you have at
> least 103 bits of address space, one could "allocate" that much memory
> on such a system, as long as you didn't try to write to all of it.


There's some debate about whether such systems are conforming.


What would be non-conforming about it? (My guess is that, given
this scenario, it's possible that malloc succeeds [ie: returns a
non-NULL value], but the program fails later when it access this
memory and the O/S discovers "oops, there's really not enough
virtual memory available to allocate".)


malloc() is supposed to "allocate space for an object" or report (by
returning a null pointer) that it's unable to do so. If it returns a
non-null pointer to memory that the program won't be able to access,
it arguably didn't really allocate it.

I'll let someone else make the argument that this behavior is
conforming.

And as a practical matter, if malloc() had visibly failed, the program
could have dealt with the error; if malloc() seems to succeed, but
some later attempt to access memory blows up, there's no way to
recover.

<OT>
Note that the program that did the allocation isn't necessarily the
one that's going to be killed. If the system decides that it's
running short on resources, it might kill processes, perhaps at
random, until the remaining processes have enough resources.
</OT>

There's something to be said for allowing this kind of
over-allocation. It can improve system efficiency if programs
commonly allocate more memory than they actually use (similar to
over-booking of airline seats). I wouldn't mind having two different
allocation functions, one that says "I want this much memory; either
guarantee that I can access it, or fail", and another that says, "I'd
like this much memory; tell me you've allocated it, but it's ok to
kill me if I try to use it". I suggest calling the former function
"malloc". You can call the latter function anything you like; I won't
be using it.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jun 20 '06 #36
Keith Thompson wrote:
Kenneth Brody <ke******@spamcop.net> writes:
[...]
(BTW, does the Standard say where variable-length arrays are stored?
Can the compiler do the equivalent of malloc/free to handle it?)


Sure.


this would make it impossible to use such constructs in a signal
handler (or other reentrant context).

Jun 20 '06 #37
"tedu" <tu@zeitbombe.org> writes:
Keith Thompson wrote:
Kenneth Brody <ke******@spamcop.net> writes:
[...]
> (BTW, does the Standard say where variable-length arrays are stored?
> Can the compiler do the equivalent of malloc/free to handle it?)


Sure.


this would make it impossible to use such constructs in a signal
handler (or other reentrant context).


Not if the implementation gets it right.

In a typical stack-based implementation, automatic objects are
allocated by advancing the stack pointer, and deallocated by setting
it back. The implementation has to do this correctly in the presence
of signal handlers.

Likewise, if VLAs are allocated by malloc, the implementation has to
free them at the right time. This might be more difficult, but I know
of no reason why it wouldn't be possible.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jun 21 '06 #38
Kenneth Brody <ke******@spamcop.net> wrote:
Keith Thompson wrote:

Kenneth Brody <ke******@spamcop.net> writes:

[...]
I've seen systems which can "allocate" memory without actually using
any memory until something is written to it. As long as you have at
least 103 bits of address space, one could "allocate" that much memory
on such a system, as long as you didn't try to write to all of it.


There's some debate about whether such systems are conforming.


What would be non-conforming about it? (My guess is that, given
this scenario, it's possible that malloc succeeds [ie: returns a
non-NULL value], but the program fails later when it access this
memory and the O/S discovers "oops, there's really not enough
virtual memory available to allocate".)


Yes. And this is anathema to solid programming and safe computer
systems.

Richard
Jun 21 '06 #39
On 2006-06-21, Richard Bos <rl*@hoekstra-uitgeverij.nl> wrote:
Kenneth Brody <ke******@spamcop.net> wrote:
Keith Thompson wrote:
>
> Kenneth Brody <ke******@spamcop.net> writes:

[...]
> > I've seen systems which can "allocate" memory without actually using
> > any memory until something is written to it. As long as you have at
> > least 103 bits of address space, one could "allocate" that much memory
> > on such a system, as long as you didn't try to write to all of it.
>
> There's some debate about whether such systems are conforming.


What would be non-conforming about it? (My guess is that, given
this scenario, it's possible that malloc succeeds [ie: returns a
non-NULL value], but the program fails later when it access this
memory and the O/S discovers "oops, there's really not enough
virtual memory available to allocate".)


Yes. And this is anathema to solid programming and safe computer
systems.


Nevertheless I believe this is what everyday GNU/Linux actually does--
apparently gives you the block then hits you with a SIGSEGV later when
you try to use it.

A bit like when you go to the bank to withdraw your money and they say,
sorry you can't have it because we've already lent it to other people,
four times over (real banks do not use the "Banker's Algorithm").
Jun 21 '06 #40
Ben C <sp******@spam.eggs> wrote:
On 2006-06-21, Richard Bos <rl*@hoekstra-uitgeverij.nl> wrote:
Kenneth Brody <ke******@spamcop.net> wrote:
What would be non-conforming about it? (My guess is that, given
this scenario, it's possible that malloc succeeds [ie: returns a
non-NULL value], but the program fails later when it access this
memory and the O/S discovers "oops, there's really not enough
virtual memory available to allocate".)


Yes. And this is anathema to solid programming and safe computer
systems.


Nevertheless I believe this is what everyday GNU/Linux actually does--
apparently gives you the block then hits you with a SIGSEGV later when
you try to use it.

A bit like when you go to the bank to withdraw your money and they say,
sorry you can't have it because we've already lent it to other people,
four times over (real banks do not use the "Banker's Algorithm").


Tuppence? *Tuppence*?

Richard
Jun 21 '06 #41
Richard Bos wrote:
Kenneth Brody <ke******@spamcop.net> wrote:
Keith Thompson wrote:
> Kenneth Brody <ke******@spamcop.net> writes:

[...]
I've seen systems which can "allocate" memory without actually
using any memory until something is written to it. As long as
you have at least 103 bits of address space, one could "allocate"
that much memory on such a system, as long as you didn't try to
write to all of it.

There's some debate about whether such systems are conforming.


What would be non-conforming about it? (My guess is that, given
this scenario, it's possible that malloc succeeds [ie: returns a
non-NULL value], but the program fails later when it access this
memory and the O/S discovers "oops, there's really not enough
virtual memory available to allocate".)


Yes. And this is anathema to solid programming and safe computer
systems.


Why should the program fail? This whole scenario is for
multi-process systems, so all that need be done is to have the
program sleep until the actual core is available. All is then
copasetic, remembering that there are no guarantees about speed.

If, in the process, the underlying system signal that it is
overloaded, that is not logically different from what happens when
the power fails. Both are beyond the scope of the language.

--
"I don't know where bin Laden is. I have no idea and really
don't care. It's not that important." - G.W. Bush, 2002-03-13
"No, we've had no evidence that Saddam Hussein was involved
with September the 11th." - George Walker Bush 2003-09-17

Jun 21 '06 #42
On 2006-06-21, CBFalconer <cb********@yahoo.com> wrote:
Richard Bos wrote:
Kenneth Brody <ke******@spamcop.net> wrote:
Keith Thompson wrote:
> Kenneth Brody <ke******@spamcop.net> writes:
[...]
> I've seen systems which can "allocate" memory without actually
> using any memory until something is written to it. As long as
> you have at least 103 bits of address space, one could "allocate"
> that much memory on such a system, as long as you didn't try to
> write to all of it.

There's some debate about whether such systems are conforming.

What would be non-conforming about it? (My guess is that, given
this scenario, it's possible that malloc succeeds [ie: returns a
non-NULL value], but the program fails later when it access this
memory and the O/S discovers "oops, there's really not enough
virtual memory available to allocate".)
Yes. And this is anathema to solid programming and safe computer
systems.


Why should the program fail? This whole scenario is for
multi-process systems, so all that need be done is to have the
program sleep until the actual core is available. All is then
copasetic, remembering that there are no guarantees about speed.


This is sometimes a good approach, but it can cause deadlock. Suppose
you have two processes (two instances of the same process let's say)
that have both allocated huge amounts of memory, and have both reached
line 6 below, and are both waiting for those 100 bytes (there are only
50 bytes left):

1: T *everything_else = malloc(LOTS);
2: ...
3:
4: T *buf = malloc(100);
5: if (buf == NULL) exit(1);
6: f(buf); /* waits for buf to actually be
available */
7: free(buf);
8: free(everything_else);

Since there are only 50 bytes left on the heap, many other processes
may end up waiting as well, which might cause deadlocks on other
resources. The user will probably have to cause the power to fail...
If, in the process, the underlying system signal that it is
overloaded, that is not logically different from what happens when
the power fails. Both are beyond the scope of the language.

Jun 21 '06 #43
Ben C wrote:
On 2006-06-21, CBFalconer <cb********@yahoo.com> wrote:
Richard Bos wrote:
Kenneth Brody <ke******@spamcop.net> wrote:
.... snip ...
What would be non-conforming about it? (My guess is that, given
this scenario, it's possible that malloc succeeds [ie: returns a
non-NULL value], but the program fails later when it access this
memory and the O/S discovers "oops, there's really not enough
virtual memory available to allocate".)

Yes. And this is anathema to solid programming and safe computer
systems.


Why should the program fail? This whole scenario is for
multi-process systems, so all that need be done is to have the
program sleep until the actual core is available. All is then
copasetic, remembering that there are no guarantees about speed.


This is sometimes a good approach, but it can cause deadlock.
Suppose you have two processes (two instances of the same process
let's say) that have both allocated huge amounts of memory, and
have both reached line 6 below, and are both waiting for those
100 bytes (there are only 50 bytes left):


Anytime you have concurrent processes contending for resources you
can have deadlocks. This is not concerned with the C language in
the least. The point is purely that optimistic filling of malloc
requests is, or can be, conforming.

--
"I don't know where bin Laden is. I have no idea and really
don't care. It's not that important." - G.W. Bush, 2002-03-13
"No, we've had no evidence that Saddam Hussein was involved
with September the 11th." - George Walker Bush 2003-09-17
Jun 21 '06 #44
Keith Thompson wrote:

"tedu" <tu@zeitbombe.org> writes:
Keith Thompson wrote:
Kenneth Brody <ke******@spamcop.net> writes:
[...]
> (BTW, does the Standard say where variable-length arrays are stored?
> Can the compiler do the equivalent of malloc/free to handle it?)

Sure.
this would make it impossible to use such constructs in a signal
handler (or other reentrant context).


Not if the implementation gets it right.

[...] Likewise, if VLAs are allocated by malloc, the implementation has to
free them at the right time. This might be more difficult, but I know
of no reason why it wouldn't be possible.


Well, it would require a reentrant version of malloc/free, lest it
fail if the signal handler were called from within malloc/free.

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th*************@gmail.com>
Jun 21 '06 #45
In article <44***************@yahoo.com>,
CBFalconer <cb********@maineline.net> wrote:
Anytime you have concurrent processes contending for resources you
can have deadlocks. This is not concerned with the C language in
the least.
However it explains why there may well be no real systems that satisfy
your theoretically true assertion:
The point is purely that optimistic filling of malloc
requests is, or can be, conforming.


-- Richard
Jun 21 '06 #46
In article <44***************@spamcop.net>,
Kenneth Brody <ke******@spamcop.net> wrote:
>> > Can the compiler do the equivalent of malloc/free to handle it?) >> Sure.
Well, it would require a reentrant version of malloc/free


Fortunately these are widely available.

-- Richard
Jun 21 '06 #47
Richard Tobin wrote:
In article <44***************@spamcop.net>,
Kenneth Brody <ke******@spamcop.net> wrote:
>> > Can the compiler do the equivalent of malloc/free to handle it?)> Sure.

Well, it would require a reentrant version of malloc/free


Fortunately these are widely available.


such as? all the implementations i'm familiar with (which may be a
limited set) have some degree of support for threads, but are certainly
not safe to call from within a signal handler.

Jun 21 '06 #48
tedu wrote:
Richard Tobin wrote:
Kenneth Brody <ke******@spamcop.net> wrote:
.... snip ...
Well, it would require a reentrant version of malloc/free


Fortunately these are widely available.


such as? all the implementations i'm familiar with (which may be
a limited set) have some degree of support for threads, but are
certainly not safe to call from within a signal handler.


Since malloc, by its very nature, is allocating a limited system
resource, namely memory, it must have protected access to various
variables. This means it cannot be truly re-entrant. However, by
use of suitable concurrency constructs it can be made thread safe.

--
"I don't know where bin Laden is. I have no idea and really
don't care. It's not that important." - G.W. Bush, 2002-03-13
"No, we've had no evidence that Saddam Hussein was involved
with September the 11th." - George Walker Bush 2003-09-17
Jun 21 '06 #49
In article <11**********************@u72g2000cwu.googlegroups .com>,
tedu <tu@zeitbombe.org> wrote:
>Well, it would require a reentrant version of malloc/free
Fortunately these are widely available.
such as? all the implementations i'm familiar with (which may be a
limited set) have some degree of support for threads, but are certainly
not safe to call from within a signal handler.


I had read that the Solaris malloc was re-entrant, but I can't find
any such statement in Sun's own documentation.

-- Richard

Jun 21 '06 #50

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

Similar topics

3
by: Sunil Menon | last post by:
Dear All, A class having no member variables and only a method sizeof(object) will return 1byte in ANSI and two bytes in Unicode. I have the answer for this of how in works in ANSI. But I don't...
2
by: Xiangliang Meng | last post by:
Hi, all. What will we get from sizeof(a class without data members and virtual functions)? For example: class abnormity { public: string name() { return "abnormity"; }
19
by: Martin Pohlack | last post by:
Hi, I have a funtion which shall compute the amount for a later malloc. In this function I need the sizes of some struct members without having an instance or pointer of the struct. As...
9
by: M Welinder | last post by:
This doesn't work with any C compiler that I can find. They all report a syntax error: printf ("%d\n", (int)sizeof (char)(char)2); Now the question is "why?" "sizeof" and "(char)" have...
7
by: dam_fool_2003 | last post by:
#include<stdio.h> int main(void) { unsigned int a=20,b=50, c = sizeof b+a; printf("%d\n",c); return 0; } out put: 24
42
by: Christopher C. Stacy | last post by:
Some people say sizeof(type) and other say sizeof(variable). Why?
8
by: junky_fellow | last post by:
Consider the following piece of code: #include <stddef.h> int main (void) { int i, j=1; char c; printf("\nsize =%lu\n", sizeof(i+j));
4
by: cs | last post by:
#include <stdio.h> #include <stdlib.h> typedef struct{ unsigned a; unsigned *b; unsigned k; }tp; tp e, *ee;
5
by: Francois Grieu | last post by:
Does this reliably cause a compile-time error when int is not 4 bytes ? enum { int_size_checked = 1/(sizeof(int)==4) }; Any better way to check the value of an expression involving sizeof...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

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.