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

char array not terminated with \0

Hi.
Suppose str is defined as follows
char str[12] = "012345678901";

Is it wrong to use functions such as
printf("%s",str)
strcmp(str2,str)
strcpy(dest,str)

(since str is an array of chars without the teminating \0)?
What could the consequence be?

../Anders
Nov 14 '05 #1
17 1980
Anders Christensen wrote:
Hi.
Suppose str is defined as follows
char str[12] = "012345678901";

Is it wrong to use functions such as
printf("%s",str)
strcmp(str2,str)
strcpy(dest,str)
Yes. After all, where would it stop?
(since str is an array of chars without the teminating \0)?
What could the consequence be?


As it invokes undefined behavior, the consequence could be *anything*.
And if you happen to be running a Death Station 9000...

;-)

HTH,
--ag

--
Artie Gold -- Austin, Texas
http://it-matters.blogspot.com (new post 12/5)
http://www.cafepress.com/goldsays
Nov 14 '05 #2
Anders Christensen wrote:
Hi.
Suppose str is defined as follows
char str[12] = "012345678901";

Is it wrong to use functions such as
printf("%s",str)
strcmp(str2,str)
strcpy(dest,str)
Yes.
(since str is an array of chars without the teminating \0)?
Right.
What could the consequence be?


Overrunning the buffer while those functions look for the '\0', causing
rhinodaemons.

Nov 14 '05 #3
Martin Ambuhl wrote:
Anders Christensen wrote:
Hi.
Suppose str is defined as follows
char str[12] = "012345678901";

Is it wrong to use functions such as
printf("%s",str)
strcmp(str2,str)
strcpy(dest,str)

Yes.
(since str is an array of chars without the teminating \0)?

Right.
What could the consequence be?

Overrunning the buffer while those functions look for the '\0', causing
rhinodaemons.

Demons, dammit, *demons*!!!

"Daemons" are OT here.

--ag

--
Artie Gold -- Austin, Texas
http://it-matters.blogspot.com (new post 12/5)
http://www.cafepress.com/goldsays
Nov 14 '05 #4
In article <pa***************************@hotmail.com>
Anders Christensen <an******@hotmail.com> wrote:

[given an array of "char" that does not have a terminating '\0', i.e.,
is not a C string...]
Is it wrong to use functions such as
printf("%s",str)
strcmp(str2,str)
strcpy(dest,str)

(since str is an array of chars without the teminating \0)?


As several others have said, yes, all three of these calls look for
the terminating '\0', which -- since there is none in the array --
triggers undefined behavior. The first call is fixable, however:
since we know that "str" -- not such a good name, as it is not a
C string -- ends after 12 "char"s, we can use:

printf("%.12s", str);

or (because it is an array, so that sizeof works):

printf("%.*s", (int)sizeof str, str);

(Note that this second call would not work if str were a pointer
pointing to this not-a-C-string 12-character array, rather than
the actual array name itself. In that case, you would get
sizeof(char *) instead of sizeof(char [12]).)

All of this means that if printf() is implemented in C, its "%s"
handler must not use strlen() if a precision has been specified.
I noticed and fixed this bug in the printf() that Keith Bostic and
I coded up for 4.4BSD. We ended up with code of the form:

case 's':
s = va_arg(ap, char *);
if (flags & PREC) { /* e.g., %.10s, %.*s */
p = memchr(s, '\0', precision);
len = p ? p - s : precision;
} else
len = strlen(s);
/*
* then output no more than 'len' bytes from the area
* pointed to by 's', obeying field-width and left- and
* right-adjustment and so on, so that, e.g., %-100.10s
* and %30s work correctly.
*/
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #5
Thanks for your answers!

Will strcpy(str,"hardcoded") end up with
str = "hardcoded\001"
or
str = "hardcoded201"

or ... ?

Nov 14 '05 #6
Anders Christensen <an******@hotmail.com> writes:
Thanks for your answers!

Will strcpy(str,"hardcoded") end up with
str = "hardcoded\001"
or
str = "hardcoded201"

or ... ?


Please provide some context. In your original article, you
wrote:

char str[12] = "012345678901";

I'll assume that same declaration still applies.

strcpy(str, "hardcoded");

will copy the characters 'h','a','r','d','c','o','d','e','d','\0' into
str at positions 0 through 9, leaving the '0' and '1' in positions 10
and 11. The result will be as if you had written:

char str[12] = "hardcoded\001";

Any function that deals with strings (strcmp, printf, etc.) will of
course ignore anything after the '\0' character; for most purposes,
the value of str is just "hardcoded".

--
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.
Nov 14 '05 #7
Anders Christensen wrote:
Thanks for your answers!

Will strcpy(str,"hardcoded") end up with
str = "hardcoded\001"
or
str = "hardcoded201"

or ... ?

Did you read the answers? Your original..

char str[12] = "012345678901";

...defines str an array 12 of char without a terminating '\0'. Not a
string! The literal "hardcoded" is an array 10 of char and includes
the '\0' at the end. After executing..

strcpy(str,"hardcoded");

...I would expect that the first 10 elements of str are in fact
"hardcoded" and that str[10] is '0' and str[11] is '1'.

Note that while (sizeof str) remains 12, strlen(str) is now 9.
--
Joe Wright mailto:jo********@comcast.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 14 '05 #8
Keith Thompson wrote:
Anders Christensen <an******@hotmail.com> writes:
Thanks for your answers!

Will strcpy(str,"hardcoded") end up with
str = "hardcoded\001"
or
str = "hardcoded201"

or ... ?
Please provide some context. In your original article, you
wrote:

char str[12] = "012345678901";

I'll assume that same declaration still applies.

strcpy(str, "hardcoded");

will copy the characters 'h','a','r','d','c','o','d','e','d','\0'

into str at positions 0 through 9, leaving the '0' and '1' in positions 10
and 11. The result will be as if you had written:

char str[12] = "hardcoded\001";


Not quite. An octal constant can be up to three octal digits long, so
\001 is actually a single byte with the value 1. You would need
something like...

char str[12] = "hardcoded\0""01";

--
Peter

Nov 14 '05 #9
<posted & mailed>

Anders Christensen wrote:
Hi.
Suppose str is defined as follows
char str[12] = "012345678901";

Is it wrong to use functions such as
printf("%s",str)
strcmp(str2,str)
strcpy(dest,str)

(since str is an array of chars without the teminating \0)?
What could the consequence be?
Those functions no where to stop reading the string by looking for the '\0'.
In the absence of it, they will sail past the end of the array. What
consequence is there? Who knows, the result is undefined. Typically either,
it will continue until a null is reached (whatever the next null in memory
is, or a memory fault will occur and something bad (crash) will result.


./Anders


--
Remove '.nospam' from e-mail address to reply by e-mail
Nov 14 '05 #10
Anders Christensen wrote:

Hi.
Suppose str is defined as follows
char str[12] = "012345678901";

Is it wrong to use functions such as
printf("%s",str)
strcmp(str2,str)
strcpy(dest,str)


It is wrong. str is not a pointer to a string.
As you can see from the description of strcpy in N869,
s2 must be a pointer to a string
in order for the effect of strcpy to be defined.

N869
7.21.2.3 The strcpy function
Synopsis
[#1]
#include <string.h>
char *strcpy(char * restrict s1,
const char * restrict s2);
Description
[#2] The strcpy function copies the string pointed to by s2
(including the terminating null character) into the array
pointed to by s1. If copying takes place between objects
that overlap, the behavior is undefined.
Returns
[#3] The strcpy function returns the value of s1.
N869 is here:
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n869/

--
pete
Nov 14 '05 #11
"Peter Nilsson" <ai***@acay.com.au> writes:
Keith Thompson wrote:

[...]
The result will be as if you had written:

char str[12] = "hardcoded\001";


Not quite. An octal constant can be up to three octal digits long, so
\001 is actually a single byte with the value 1. You would need
something like...

char str[12] = "hardcoded\0""01";


Oops, you're right. You could also write it as

char str[12] = "hardcoded\00001";

but that's not as clear.

--
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.
Nov 14 '05 #12
hi,
statements like char str[12]="012345678901", dont suffix "\0" after the
array of characters or strings on its own . or the programmer has to
give it explicitly??????????????

Chris Torek wrote:
In article <pa***************************@hotmail.com>
Anders Christensen <an******@hotmail.com> wrote:

[given an array of "char" that does not have a terminating '\0', i.e., is not a C string...]
Is it wrong to use functions such as
printf("%s",str)
strcmp(str2,str)
strcpy(dest,str)

(since str is an array of chars without the teminating \0)?


As several others have said, yes, all three of these calls look for
the terminating '\0', which -- since there is none in the array --
triggers undefined behavior. The first call is fixable, however:
since we know that "str" -- not such a good name, as it is not a
C string -- ends after 12 "char"s, we can use:

printf("%.12s", str);

or (because it is an array, so that sizeof works):

printf("%.*s", (int)sizeof str, str);

(Note that this second call would not work if str were a pointer
pointing to this not-a-C-string 12-character array, rather than
the actual array name itself. In that case, you would get
sizeof(char *) instead of sizeof(char [12]).)

All of this means that if printf() is implemented in C, its "%s"
handler must not use strlen() if a precision has been specified.
I noticed and fixed this bug in the printf() that Keith Bostic and
I coded up for 4.4BSD. We ended up with code of the form:

case 's':
s = va_arg(ap, char *);
if (flags & PREC) { /* e.g., %.10s, %.*s */
p = memchr(s, '\0', precision);
len = p ? p - s : precision;
} else
len = strlen(s);
/*
* then output no more than 'len' bytes from the area
* pointed to by 's', obeying field-width and left- and
* right-adjustment and so on, so that, e.g., %-100.10s
* and %30s work correctly.
*/
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to

spammers.

Nov 14 '05 #13
th********@rediffmail.com wrote:
hi,
statements like char str[12]="012345678901", dont suffix "\0" after the
array of characters or strings on its own . or the programmer has to
give it explicitly??????????????

Don't top post. I've snipped the original message, as yours provides
enough context.

The issue in the definition above is that the array `str' is declared to
have sufficient room for only 12 chars; the '\0' would be appended *if
there was room for it*.

HTH,
--ag

--
Artie Gold -- Austin, Texas
http://it-matters.blogspot.com (new post 12/5)
http://www.cafepress.com/goldsays
Nov 14 '05 #14
On Sun, 16 Jan 2005 23:41:37 GMT, Keith Thompson
<ks***@mib.org> wrote:
Anders Christensen <an******@hotmail.com> writes:
Thanks for your answers!

Will strcpy(str,"hardcoded") end up with
str = "hardcoded\001"
or
str = "hardcoded201"

or ... ?


Please provide some context. In your original article, you
wrote:

char str[12] = "012345678901";

I'll assume that same declaration still applies.

strcpy(str, "hardcoded");

will copy the characters 'h','a','r','d','c','o','d','e','d','\0' into
str at positions 0 through 9, leaving the '0' and '1' in positions 10
and 11. The result will be as if you had written:

char str[12] = "hardcoded\001";


No, it won't, that would cause it to contain

'h', 'a', 'r', 'd', 'c', 'o', 'd', 'e', 'd', '\001', '\0', '\0'

I suspect you meant:

char str[12] = "hardcoded\00001";

Chris C
Nov 14 '05 #15

"Artie Gold" <ar*******@austin.rr.com> wrote in message
news:35*************@individual.net...
th********@rediffmail.com wrote:
hi,
statements like char str[12]="012345678901", dont suffix "\0" after the
array of characters or strings on its own . or the programmer has to
give it explicitly??????????????

Don't top post. I've snipped the original message, as yours provides
enough context.

The issue in the definition above is that the array `str' is declared to
have sufficient room for only 12 chars; the '\0' would be appended *if
there was room for it*.


For completeness:

Also, a '\0' would be appended if the size were computed
by the compiler, as happens when no size is explicitly specified:

char str[] = "abc"; /* array size is 4 */

-Mike
Nov 14 '05 #16
Chris Croughton <ch***@keristor.net> writes:
On Sun, 16 Jan 2005 23:41:37 GMT, Keith Thompson <ks***@mib.org> wrote:

[...]
The result will be as if you had written:

char str[12] = "hardcoded\001";


No, it won't, that would cause it to contain

'h', 'a', 'r', 'd', 'c', 'o', 'd', 'e', 'd', '\001', '\0', '\0'

I suspect you meant:

char str[12] = "hardcoded\00001";


Quite correct, thanks.

--
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.
Nov 14 '05 #17
Thanx again for your answers on string!

../Anders

Nov 14 '05 #18

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

Similar topics

8
by: ali | last post by:
Hi, I'm having a problem understanding the reason for output on the following code: #include <iostream.h> int main() {
10
by: techie | last post by:
I'm creating a class BookType that will store information about books. Each book type can have up to 4 authors. I defined a new type for an array of char: typedef char array4_t; This will...
19
by: Rick | last post by:
Hi, I was wondering, can it be safely assumed that any function that returns a *char will return a NULL terminated string? Or does the function explicitly mention this always (and the ones that...
2
by: vikas | last post by:
I have following structure in c++. typedef struct MMF_result_struct { int action; char text; int cols,rows; int month,day,year; } MMF_result; Now this structure is shared between C++ and C#...
10
by: fei.liu | last post by:
Consider the following sample code char * ptr = "hello"; char carray = "hello"; int main(void){ } What does the standard have to say about the storage requirement about ptr and carray? Is...
2
by: Michael | last post by:
Hi, How to understand the difference between the following three. My understanding is the number in bracket minus one is the max number of chars to store in the char array , right? ...
6
by: MattWilson.6185 | last post by:
Hello! I am trying to convert a char * to a LPWSTR, and I am going absolutly mad! I can't find anything besides typle L"string" Unfortunetaly I can't use that... basicaly the setup is ...
3
by: =?Utf-8?B?cmtwYXQ=?= | last post by:
i'm calling a C++ DLL from C#. here's C++ interface: char* __cdecl SendCmd(void* handle, char* cmd, char* data, char* buffer); here's my call in C#: unsafe public static extern byte* SendCmd...
11
by: Dennis Jones | last post by:
Hi all, 1) Let's say you have two char 's of the same size. How would you write a no-fail swap method for them? For example: class Test { char s; void swap( Test &rhs ) {
2
by: nagesh0280 | last post by:
Hi experts, I'm from a Verilog HDL background and trying to learn C. There are a lot of similarities between Verilog and C but the concept of char arrays and strings has me confused. I'd...
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...
1
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: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
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)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.