473,666 Members | 2,080 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

String and null character

Some questions about strings: this is the extracted piece of my test code:

/** **/

char *arry;
arry = malloc(30*sizeo f(arry));

arry[0] = 'B';
arry[1] = 'S';
arry[2] = 'c';

/** **/

The questions are:

1. Now does the variable arry contain the null character immediately because
of malloc?

2. or I should append '0' at arry[3] ? (which in fact what I did next, but
when testing the compiler without '\0', it worked (??)

Because in both cases (whether I append '\0' or not), if I use the
functions atoi or any other string functions, the compiler
does not give warning or error message, what happened?

Thanks in advance
Nov 13 '05 #1
13 6285
"Chapman" <ch**@hotmail.c om> wrote:
Some questions about strings: this is the extracted piece of my test code:

/** **/

char *arry;
arry = malloc(30*sizeo f(arry)); You allocate memory to hold 30 pointers-to-character, which is obviously
not your intention; make this:

arry = malloc( 30 * sizeof *arry );

arry[0] = 'B';
arry[1] = 'S';
arry[2] = 'c';

/** **/

The questions are:

1. Now does the variable arry contain the null character immediately because
of malloc? No.

2. or I should append '0' at arry[3] ? If you intend to use it as a string: yes.
(which in fact what I did next, but
when testing the compiler without '\0', it worked (??) This was just (bad) luck; virtually *anything* could have happened.

Because in both cases (whether I append '\0' or not), if I use the
functions atoi or any other string functions, the compiler
does not give warning or error message, what happened?

The compiler cannot check something that gets allocated and altered at
run-time. You have to make sure your strings are '\0'-terminated.

Regards

Irrwahn
--
Close your eyes and press escape three times.
Nov 13 '05 #2

"Chapman" <ch**@hotmail.c om> wrote in message
news:il******** ************@ne ws-server.bigpond. net.au...
Some questions about strings: this is the extracted piece of my test code:

/** **/

char *arry;
arry = malloc(30*sizeo f(arry));
If you want to allocate a buffer to hold a string, you should write

arry = malloc(30); /* This way is correct. "sizeof char" is defined as 1
byte, you don't need to use sizeof on this */

or

arry = malloc(30 * sizeof *arry) /* You should use sizeof on "*arry" (which
is a single char), not char* (which is a pointer. I think this is not what
you want, right ? ). Also, don't use "sizeof( variable )" , use "sizeof
variable" or "sizeof(variabl e type)" instead. */


arry[0] = 'B';
arry[1] = 'S';
arry[2] = 'c';

/** **/

The questions are:

1. Now does the variable arry contain the null character immediately because of malloc?
No. If you want to fill all the elements by zero after allocated, you can
consider "calloc"
2. or I should append '0' at arry[3] ?
Yes.

(which in fact what I did next, but when testing the compiler without '\0', it worked (??)

Don't believe this, you are just lucky.
Because in both cases (whether I append '\0' or not), if I use the
functions atoi or any other string functions, the compiler
does not give warning or error message, what happened?


Why should it give warning or error ?
--
Jeff
-je6543 at yahoo.com
Nov 13 '05 #3
"Chapman" <ch**@hotmail.c om> wrote in message news:<il******* *************@n ews-server.bigpond. net.au>...
Some questions about strings: this is the extracted piece of my test code:

/** **/

char *arry;
arry = malloc(30*sizeo f(arry));
ITYM

arry = malloc (30 * sizeof *arry);

The type of arry is char*; the type of *arry is char.

arry[0] = 'B';
arry[1] = 'S';
arry[2] = 'c';

/** **/

The questions are:

1. Now does the variable arry contain the null character immediately because
of malloc?

No. malloc() does not initialize the allocated memory to any specific
value. Assume it contains garbage. If you need the memory to be
initialized to 0 when allocating it, use calloc().
2. or I should append '0' at arry[3] ? (which in fact what I did next, but
when testing the compiler without '\0', it worked (??)
Luck. The memory you allocated just happened to be zeroed out, but
you can't rely on that behavior.

Because in both cases (whether I append '\0' or not), if I use the
functions atoi or any other string functions, the compiler
does not give warning or error message, what happened?

Thanks in advance


The string functions will walk through memory starting at the point
you specify until they see a nul terminator (0). If you forget to put
a nul terminator in your buffer, the string functions will happily
read or write past it until they either find one or try to read or
write a protected or invalid memory address, causing a trap.

Either way, forgetting to append a nul terminator to a dynamically
allocated buffer is a condition that only occurs when the program is
run; your compiler can't warn you about something that it can't
predict.
Nov 13 '05 #4

"Jeff" <no*****@notexi st.com> wrote in message
news:bk******** ***@news.hgc.co m.hk...

"Chapman" <ch**@hotmail.c om> wrote in message
news:il******** ************@ne ws-server.bigpond. net.au...
Some questions about strings: this is the extracted piece of my test code:
/** **/

char *arry;
arry = malloc(30*sizeo f(arry));
If you want to allocate a buffer to hold a string, you should write

arry = malloc(30); /* This way is correct. "sizeof char" is defined as 1
byte, you don't need to use sizeof on this */

or

arry = malloc(30 * sizeof *arry) /* You should use sizeof on "*arry"

(which is a single char), not char* (which is a pointer. I think this is not what you want, right ? ). Also, don't use "sizeof( variable )" , use "sizeof
variable" or "sizeof(variabl e type)" instead. */
Thanks for the explanation Jeff.
The questions are:

1. Now does the variable arry contain the null character immediately

because
of malloc?


No. If you want to fill all the elements by zero after allocated, you can
consider "calloc"
2. or I should append '0' at arry[3] ?


Yes.

(which in fact what I did next, but
when testing the compiler without '\0', it worked (??)


Don't believe this, you are just lucky.


I could not believe it either, and everytime I run the program without
appending the '\0', it was alright.
Something wrong with gcc ? Following the standard, I appended '\0', just
curious why it happened without warning.
It is not about being lucky, or probably the function definitions with gcc
is 'relaxed' about the '\0' ??
Because in both cases (whether I append '\0' or not), if I use the
functions atoi or any other string functions, the compiler
does not give warning or error message, what happened?


Why should it give warning or error ?


It should gave me error when I run it and the string did not have the '\0',
but it didn't
--
Jeff
-je6543 at yahoo.com

Nov 13 '05 #5

"Chapman" <ch**@yahoo.com > wrote in message

I could not believe it either, and everytime I run the program without
appending the '\0', it was alright.
Something wrong with gcc ? Following the standard, I appended '\0',
just curious why it happened without warning.
It is not about being lucky, or probably the function definitions with gcc
is 'relaxed' about the '\0' ??
String functions will generally fail if passed a non-NUL terminated string.

However it is quite common for garbage memory to contain a lot of zeroes,
and you must have just hit a zero. It's also possible that your version of
malloc() zeroes memory, however you can't rely on this behaviour.
It should gave me error when I run it and the string did not have the
'\0', but it didn't

The following code is OK

char *str = calloc(1,100);
str[0] = 'F';
str[1] = 'R';
str[2] = 'E';
str[3] = 'D';
printf("%s\n", str);

This is because calloc() is guaranteed to zero memory.

The compiler is not clever enough to distinguish between the function
calloc() and malloc(), and realise that in your case you are setting up a
string which is not NUL-terminated. This is because C is such a low-level
language - strings are just handled as arrays of bytes in memory.
Nov 13 '05 #6
"Malcolm" <ma*****@55bank .freeserve.co.u k> wrote:

"Chapman" <ch**@yahoo.com > wrote in message

I could not believe it either, and everytime I run the program without
appending the '\0', it was alright.
Something wrong with gcc ? Following the standard, I appended '\0',
just curious why it happened without warning.
It is not about being lucky, or probably the function definitions with gcc
is 'relaxed' about the '\0' ??

String functions will generally fail if passed a non-NUL terminated string.

^^^^^^^^^^^^^^^ ^^^^
Nit-pick: ... will generally invoke undefined behaviour ...

<SNIP>

Regards

Irrwahn
--
Close your eyes and press escape three times.
Nov 13 '05 #7
"Chapman" <ch**@yahoo.com > wrote in message news:<9m******* **************@ news-server.bigpond. net.au>...
"Jeff" <no*****@notexi st.com> wrote in message
news:bk******** ***@news.hgc.co m.hk...

"Chapman" <ch**@hotmail.c om> wrote in message
news:il******** ************@ne ws-server.bigpond. net.au...
Some questions about strings: this is the extracted piece of my test code:
/** **/

char *arry;
arry = malloc(30*sizeo f(arry));


If you want to allocate a buffer to hold a string, you should write

arry = malloc(30); /* This way is correct. "sizeof char" is defined as 1
byte, you don't need to use sizeof on this */

or

arry = malloc(30 * sizeof *arry) /* You should use sizeof on "*arry"

(which
is a single char), not char* (which is a pointer. I think this is not

what
you want, right ? ). Also, don't use "sizeof( variable )" , use "sizeof
variable" or "sizeof(variabl e type)" instead. */

Thanks for the explanation Jeff.
The questions are:

1. Now does the variable arry contain the null character immediately because of malloc?


No. If you want to fill all the elements by zero after allocated, you can
consider "calloc"
2. or I should append '0' at arry[3] ?


Yes.

(which in fact what I did next, but
when testing the compiler without '\0', it worked (??)


Don't believe this, you are just lucky.


I could not believe it either, and everytime I run the program without
appending the '\0', it was alright.
Something wrong with gcc ? Following the standard, I appended '\0', just
curious why it happened without warning.
It is not about being lucky, or probably the function definitions with gcc
is 'relaxed' about the '\0' ??
Because in both cases (whether I append '\0' or not), if I use the
functions atoi or any other string functions, the compiler
does not give warning or error message, what happened?


Why should it give warning or error ?


It should gave me error when I run it and the string did not have the '\0',
but it didn't


You run it on some other platform it would possibly give you an error
eventhough the chances of having a runtime error are more than those
of a compile time error. It is as a matter of fact difficult to get to
know if you are setting or not setting the null character, consider
this

while ( some_condition )
{
c = getchar();
malloced_charac ter_array [ i ] = c;
i += 1;
}

During complile time it is quite difficult to determine as to if what
the user would set the value to be.
BTW compiler is not supposed to give any error and I think I won't be
wrong if I could say that the compiler is not supposed to give error
even for a completly invalid program

even if you type garbage in your source file, it is quite unreasonable
but true that a compiler can give you a message of the form of

"succesfull y built".
HTH
PS IIRC someone had a website which showed a missile heading back to
the carrier which shot them in case of program exhibiting a UB, can
anybody provide that link.

--

Imanpreet Singh Arora
imanpreet_arora AT yahoo DOT co DOT in
Nov 13 '05 #8
On Tue, 16 Sep 2003 00:55:30 +0200, Irrwahn Grausewitz
<ir*****@freene t.de> wrote in comp.lang.c:
"Malcolm" <ma*****@55bank .freeserve.co.u k> wrote:

"Chapman" <ch**@yahoo.com > wrote in message

I could not believe it either, and everytime I run the program without
appending the '\0', it was alright.
Something wrong with gcc ? Following the standard, I appended '\0',
just curious why it happened without warning.
It is not about being lucky, or probably the function definitions with gcc
is 'relaxed' about the '\0' ??
String functions will generally fail if passed a non-NUL terminated string.

^^^^^^^^^^^^^^^ ^^^^
Nit-pick: ... will generally invoke undefined behaviour ...

^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^
Even more nit pick: will ALWAYS invoke undefined behavior, which
generally causes a program to fail.

<SNIP>

Regards

Irrwahn


--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
Nov 13 '05 #9
mi************@ yahoo.com (Minti) wrote:

<SNIP>

BTW compiler is not supposed to give any error and I think I won't be
wrong if I could say that the compiler is not supposed to give error
even for a completly invalid program

even if you type garbage in your source file, it is quite unreasonable
but true that a compiler can give you a message of the form of

"succesfull y built".

<SNIP>

Hmm, consider this quote from n843:

5.1.1.3 Diagnostics

[#1] A conforming implementation shall produce at least one
diagnostic message (identified in an implementation-defined
manner) if a preprocessing translation unit or translation
unit contains a violation of any syntax rule or constraint,
even if the behavior is also explicitly specified as
undefined or implementation-defined. Diagnostic messages
need not be produced in other circumstances.7 )

[#2] EXAMPLE An implementation shall issue a diagnostic for
the translation unit:

char i;
int i;

because in those cases where wording in this International
Standard describes the behavior for a construct as being
both a constraint error and resulting in undefined behavior,
the constraint error shall be diagnosed.

[...]

Regards

Irrwahn
--
My opinions are not those of my ex-employer.
Nov 13 '05 #10

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

Similar topics

7
5541
by: BlueDragon | last post by:
I don't know enough math to demonstrate that any numerical operation with a null should yield a null; although I would guess that it's true. I just don't buy it, however, when dealing with strings and nulls. In a simple table with first, middle and last name columns, I would infer that a null value in the middle name column means the HR person forgot to ask. A zero length string, however, tells me HR did ask and there is no middle name....
16
17409
by: Don Starr | last post by:
When applied to a string literal, is the sizeof operator supposed to return the size of the string (including nul), or the size of a pointer? For example, assuming a char is 1 byte and a char * is 4 bytes, should the following yield 4, 5, of something else? (And, if something else, what determines the result?) char x = "abcd"; printf( "%d\n", sizeof( x ) ); -Don
14
12917
by: Charles L | last post by:
I don't know if this is a stupid quesiton or not. I would like to know how to convert an array of characters generated from a previous operation to a string ie how do I append a null character at the end? I haven't been able to do it so far. Is there a string function I can use? Can anyone help? Charles L
7
2606
by: spike | last post by:
Im writing a program to search for a string in a binary file. And it works. The problem is: It is sooo slow! how can i make it faster? It takes 27 seconds just to search a 5 meg file. I guess it has something to do with the strequal() function... Btw, thanks to all of you who answered last time! code: ------------------------------------------------------------------------- #include <stdio.h>
10
14477
by: lchian | last post by:
Hi, For two stl strings s1 and s2, I got different results from strcmp(s1.c_str(), s2.c_str()) and s1.compare(s2) can someone explain what these functions do? It seems that strcmp gives the "right" (i.e.wysiwyg) answer while compare() does not.
33
3663
by: Jordan Tiona | last post by:
How can I make one of these? I'm trying to get my program to store a string into a variable, but it only stores one line. -- "No eye has seen, no ear has heard, no mind can conceive what God has prepared for those who love him" 1 Cor 2:9
12
1976
by: semut | last post by:
Given that the string is of null terminated type. What could be the possible causes (by experience) the string to have no null terminated and cause buffer overflow later. I know it is quite broad, just like to find out the causes as much as possible so that I could impose stricter checking toward my codes. note: I could not use std::string cause it will require a total rewrite. thanks.
0
6547
by: Brenda | last post by:
We are on DB2, AIX fixpak 14 This error happens when running PeopleSoft PeopleCode Application Engine process. I have checked other posts out here and it seems like others who have reported it seem to be saying their is a problem with the way DB2 is interpreting a string statement with a varchar field. -- 00.03.40 ..(ZZ_EX_NOTS.SendMail.Send3) (PeopleCode)
3
5089
by: jacob navia | last post by:
Abstract: Continuing the discussion about abstract data types, in this discussion group, a string collection data type is presented, patterned after the collection in C# and similar languages (Java). It stores character strings, and resizes itself to accommodate new strings when needed. Interface: ----------
3
12570
by: amija0311 | last post by:
Hi, I am new using DB2 9.1 database by windows base. I want to query the data that contain string then translate the string into integer using DB2. The problems is If the data is null, i got the problem to translate. How to translate string also allow null data to integer. If null data it will read as space. My Data :- GEOSEG_ID SEQNO
0
8445
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
8781
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8551
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
8640
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
6198
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
4369
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2771
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
2011
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1776
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.