473,785 Members | 2,831 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

max strlen at compile time?



Hi,

can I use the preprocessor, using sizeof(a)/sizeof(a[0]) to yield an
error for too long strings?

Like:

#define CRYPT(a) \
#if sizeof(a)/sizeof(a[0]) 31 \
xCRYPT(a) \
#else\
#error xy\
#endif

(which of course doe not work)
--
-Gernot
int main(int argc, char** argv) {printf
("%silto%c%cf%c gl%ssic%ccom%c" , "ma", 58, 'g', 64, "ba", 46, 10);}

_______________ _______________ __________
Looking for a good game? Do it yourself!
GLBasic - you can do
www.GLBasic.com
Aug 1 '06 #1
14 4551
Gernot Frisch said:
>

Hi,

can I use the preprocessor, using sizeof(a)/sizeof(a[0]) to yield an
error for too long strings?
No, the preprocessor doesn't resolve uses of sizeof - that's done by the
compiler later on.

--
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)
Aug 1 '06 #2
In article <jK************ *************** ***@bt.com>,
Richard Heathfield <in*****@invali d.invalidwrote:
>can I use the preprocessor, using sizeof(a)/sizeof(a[0]) to yield an
error for too long strings?
>No, the preprocessor doesn't resolve uses of sizeof - that's done by the
compiler later on.
However, sizeof does produce a constant value, and there have been
tricks posted here in the past to detect errors of this kind at
compile time.

-- Richard
Aug 1 '06 #3
Richard Tobin said:
In article <jK************ *************** ***@bt.com>,
Richard Heathfield <in*****@invali d.invalidwrote:
>>can I use the preprocessor, using sizeof(a)/sizeof(a[0]) to yield an
error for too long strings?
>>No, the preprocessor doesn't resolve uses of sizeof - that's done by the
compiler later on.

However, sizeof does produce a constant value, and there have been
tricks posted here in the past to detect errors of this kind at
compile time.
Yes, but he specifically asked about the preprocessor. (Yeah, I know, the
subject line says "compile 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)
Aug 1 '06 #4

"Richard Heathfield" <in*****@invali d.invalidschrie b im Newsbeitrag
news:Bd******** ************@bt .com...
Richard Tobin said:
>In article <jK************ *************** ***@bt.com>,
Richard Heathfield <in*****@invali d.invalidwrote:
>>>can I use the preprocessor, using sizeof(a)/sizeof(a[0]) to yield
an
error for too long strings?
>>>No, the preprocessor doesn't resolve uses of sizeof - that's done
by the
compiler later on.

However, sizeof does produce a constant value, and there have been
tricks posted here in the past to detect errors of this kind at
compile time.

Yes, but he specifically asked about the preprocessor. (Yeah, I
know, the
subject line says "compile time"...)
Very nice. So - can somone please show me how to check for max
stringlength at _compile time_?
Aug 2 '06 #5
Gernot Frisch said:
>
"Richard Heathfield" <in*****@invali d.invalidschrie b im Newsbeitrag
news:Bd******** ************@bt .com...
<snip>
>>
Yes, but he specifically asked about the preprocessor. [...]

Very nice. So - can somone please show me how to check for max
stringlength at _compile time_?
Oh, okay. Let's take your original example:

#define CRYPT(a) \
#if sizeof(a)/sizeof(a[0]) 31 \
xCRYPT(a) \
#else\
#error xy\
#endif

Now let me just hack that to give a useful name that doesn't look silly when
quoted in ordinary text:

#define CRYPT(Array) \
#if sizeof(Array)/sizeof(Array[0]) 31 \
xCRYPT(Array) \
#else\
#error xy\
#endif

What we want, then, is a compile-time error if the size of Array exceeds 31.
Here's how:

char Array[SUSPECT_LENGTH] = {0};
char Error_ArrayIsTo oLong[((sizeof Array / sizeof Array[0] <= OKAY_LENGTH) *
2) - 1] = {0};

With OKAY_LENGTH set at 31 and SUSPECT_LENGTH at 31, I get:

gcc -W -Wall -ansi -pedantic -Wformat-nonliteral -Wcast-align
-Wpointer-arith -Wbad-function-cast -Wmissing-prototypes
-Wstrict-prototypes -Wmissing-declarations -Winline -Wundef
-Wnested-externs -Wcast-qual -Wshadow -Wconversion -Wwrite-strings
-Wno-conversion -ffloat-store -O2 -g -pg -c -o foo.o foo.c
foo.c: In function `main':
foo.c:9: warning: unused variable `Error_ArrayIsT ooLong'

With OKAY_LENGTH set at 31 and SUSPECT_LENGTH at 32, I get:

gcc -W -Wall -ansi -pedantic -Wformat-nonliteral -Wcast-align
-Wpointer-arith -Wbad-function-cast -Wmissing-prototypes
-Wstrict-prototypes -Wmissing-declarations -Winline -Wundef
-Wnested-externs -Wcast-qual -Wshadow -Wconversion -Wwrite-strings
-Wno-conversion -ffloat-store -O2 -g -pg -c -o foo.o foo.c
foo.c: In function `main':
foo.c:9: size of array `Error_ArrayIsT ooLong' is negative
foo.c:9: warning: unused variable `Error_ArrayIsT ooLong'
make: *** [foo.o] Error 1

QED.

--
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)
Aug 2 '06 #6
What we want, then, is a compile-time error if the size of Array
exceeds 31.
Here's how:

char Array[SUSPECT_LENGTH] = {0};
char Error_ArrayIsTo oLong[((sizeof Array / sizeof Array[0] <=
OKAY_LENGTH) *
2) - 1] = {0};
foo.c: In function `main':
foo.c:9: size of array `Error_ArrayIsT ooLong' is negative
foo.c:9: warning: unused variable `Error_ArrayIsT ooLong'

Very clever! Thank you.
Aug 2 '06 #7
Richard Heathfield writes:
What we want, then, is a compile-time error if the size of Array
exceeds 31. Here's how:

char Array[SUSPECT_LENGTH] = {0};
char Error_ArrayIsTo oLong[((sizeof Array / sizeof Array[0] <= OKAY_LENGTH) *
2) - 1] = {0};
A lot of compilers are lax about error checking in one way or another -
I think I've seen one which converted that negative size to unsigned,
for example. So I prefer to violate two constraints, just in case:

#define CHECK_CONSTRAIN T(name, test) \
typedef struct { \
int constraint_##na me: (test) ? 1 : -999; \
} constraint_##na me[(test) ? 1 : -999]

CHECK_CONSTRAIN T(Array_size, sizeof Array/sizeof Array[0] <= OKAY_LENGTH)

--
Hallvard
Aug 2 '06 #8

"Hallvard B Furuseth" <h.**********@u sit.uio.noschri eb im
Newsbeitrag news:hb******** ******@bombur.u io.no...
Richard Heathfield writes:
>What we want, then, is a compile-time error if the size of Array
exceeds 31. Here's how:

char Array[SUSPECT_LENGTH] = {0};
char Error_ArrayIsTo oLong[((sizeof Array / sizeof Array[0] <=
OKAY_LENGTH) *
2) - 1] = {0};

A lot of compilers are lax about error checking in one way or
another -
I think I've seen one which converted that negative size to
unsigned,
for example. So I prefer to violate two constraints, just in case:

#define CHECK_CONSTRAIN T(name, test) \
typedef struct { \
int constraint_##na me: (test) ? 1 : -999; \
} constraint_##na me[(test) ? 1 : -999]

CHECK_CONSTRAIN T(Array_size, sizeof Array/sizeof Array[0] <=
OKAY_LENGTH)
how about this:

{
const char err_str_too_lon g[
(sizeof(str)/sizeof(str[0]) <= 32)+1
] ={0,0};
}

which makes an [1] or a [2], and yields an error:
error C2078: too many initializers

which is quite informative, I think...

Is it x-compiler compatible?
Aug 2 '06 #9
Gernot Frisch writes:
>"Hallvard B Furuseth" <h.**********@u sit.uio.noschri eb im
>>Richard Heathfield writes:
>>What we want, then, is a compile-time error if the size of Array
exceeds 31. Here's how:
(...)

how about this:

{
const char err_str_too_lon g[
(sizeof(str)/sizeof(str[0]) <= 32)+1
] ={0,0};
}

which makes an [1] or a [2], and yields an error:
error C2078: too many initializers

which is quite informative, I think...
Heh. Quite fitting for that particular error. gcc only gives a warning
about it though. Compilation only fails if you use gcc -pedantic-errors.
Hmm. I'll suggest to change that and see what they say. It's not a bug
do behave like that, just unexpected.

One matter I didn't notice at first is that your and Richard's variants
generate data, while mine doesn't (it just makes a typedef).

--
Hallvard
Aug 2 '06 #10

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

Similar topics

45
11729
by: Matt Parkins | last post by:
Hi, (I realise this probably isn't precisely the right group for this - could someone direct me to the appropriate group to post this question? - thanks !) I'm using Visual C++ 2005 Express Edition Beta (free download from MS - hooray!), and everything works fine, except I get warnings back on the use of some functions, strlen() for example, saying that the function has been deprecated - although they do still work (which is I guess...
12
4428
by: Nollie | last post by:
I need to write a couple of my own string manipulation routines (e.g. a strcpy() alternative that returns the number of chars copied). I've started with one of the simpler functions, strlen(). I've written a very simple version call StringLength(), but it performs significantly slower than its CRT counterparts. Here's my implementation: inline unsigned int StringLength( const char *pszString ) { unsigned int cch = 0;
21
8491
by: sugaray | last post by:
hi, it just came up my mind that since we can get the length of any given string literal S with 'sizeof S-1', so, what's the merit of library function strlen()'s existence ? thanx in advance for your instruction.
81
7354
by: Matt | last post by:
I have 2 questions: 1. strlen returns an unsigned (size_t) quantity. Why is an unsigned value more approprate than a signed value? Why is unsighned value less appropriate? 2. Would there be any advantage in having strcat and strcpy return a pointer to the "end" of the destination string rather than returning a
33
2976
by: apropo | last post by:
what is wrong with this code? someone told me there is a BAD practice with that strlen in the for loop, but i don't get it exactly. Could anyone explain me in plain english,please? char *reverse(char *s) { int i; char *r; if(!s) return NULL;//ERROR r=calloc(strlen(s)+1,sizeof(char));
66
7789
by: roy | last post by:
Hi, I was wondering how strlen is implemented. What if the input string doesn't have a null terminator, namely the '\0'? Thanks a lot Roy
7
2886
by: Duke | last post by:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv) { char *s = "hello strlen"; printf("%s has %d chars.\n", s, strlen(s)); //the above strlen function execute correctly char *msg1 = "abcdefghijklmnopqrstuvwxyz";
53
717
by: ¬a\\/b | last post by:
strlen is wrong because can not report if there is some error e.g. char *a; and "a" point to an array of size=size_t max that has no 0 in it
11
3399
by: Bill Cunningham | last post by:
Strncat is supposed to be better than strcat for some reason I've read. Is this because of a potential buffer overflow? I have compiled properly and used strlen too and I just wonder what is the need to return a strlen? Has anyone used quite abit anyway the strlen function? Bill
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10324
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10090
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9949
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4050
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.