473,830 Members | 2,022 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is the behaviour defined

Hi,
A collegue of mine is of the opinion that the behaviour of the
following program is defined,but I am a little apprehensive.

#include<stdio. h>
#include<string .h>

int main()
{
char *c;
c = &c;
strcpy(c,"abc") ;
puts(&c);
retun 0;
}

The program prints the same value "abc" on multiple platforms and I even
tried it with multiple compilers.I can make out that its trying to write
to the pointer address and so probably the max it can write is 3 bytes +
'\0'.But even if I try to copy more that 4 bytes it prints the whole
string without any crashes.

Changed line >> strcpy(c,"abcde fg");

Now I know that this behaviour is undefined(writi ng more than 4 bytes)
as the sizeof the pointer is 4 bytes(on the machine I tested on).

Can anyone comment if this is compliant code and is the behaviour
guaranteed.

Thanks
~
Nov 15 '05 #1
31 1372
> int main()
{
char *c;
c = &c;
strcpy(c,"abc") ;
puts(&c);
retun 0;
}

It should be return 0;
The spell of the return is wrong in the test program above.I did not
have it in my test program which I compiled , but added it while
composing this mail , of the fear of getting battered by the C language
purists ;).
Nov 15 '05 #2
grid wrote on 01/10/05 :
A collegue of mine is of the opinion that the behaviour of the following
program is defined,
At minimum, it's implementation-dependent. But the result of putting
any value in a pointer may have an undefined result (trap
representation) . There is a possibility of undefined behaviour.
but I am a little apprehensive.
You can!
#include<stdio. h>
#include<string .h>

int main()
{
char *c;
c = &c;
Types are incompatible. (c is a char * and &c is a char**)
strcpy(c,"abc") ;
The result of the 'sizeof char* == sizeof "abc"' expression is
implementation-dependent.

You need a space of 4 bytes for "abc".

For example, on a x86 in real mode (16-bit) model small, pointers are
16-bit wide, which means 2 bytes on this machine. Too small for "abc"
puts(&c);
retun 0;
}


--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

..sig under repair
Nov 15 '05 #3
"grid" <pr******@gmail .com> wrote in message
news:QK******** ****@news.oracl e.com...
A collegue of mine is of the opinion that the behaviour of the
following program is defined,but I am a little apprehensive.

#include<stdio. h>
#include<string .h>

int main()
{
char *c;
c = &c;
strcpy(c,"abc") ;
puts(&c);
retun 0;
}


The above code is broken. You attempt to store 4 chars/bytes
(1+strlen("abc" )==4) to the variable c, but you don't know whether c
(pointer to a char) is big enough to hold 4 chars/bytes. On some platforms
it can be 2 or even 1, hence you're risking to overwrite something else.
Tell your collegue first to learn C better before advising a code such as
the above.

Alex
Nov 15 '05 #4
>> char *c;
c = &c;

Types are incompatible. (c is a char * and &c is a char**)


That is just to make c point to the first byte of the string.We will
anyhow require a cast for this to silence the compiler, since they are
really incompatible types as you mentioned

c = (char *)&c;

Thanks,
~
Nov 15 '05 #5
grid wrote on 01/10/05 :
char *c;
c = &c;


Types are incompatible. (c is a char * and &c is a char**)


That is just to make c point to the first byte of the string.We will anyhow
require a cast for this to silence the compiler, since they are really
incompatible types as you mentioned

c = (char *)&c;


The result of the cast is implementation-dependent.

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

..sig under repair
Nov 15 '05 #6
> The above code is broken. You attempt to store 4 chars/bytes
(1+strlen("abc" )==4) to the variable c, but you don't know whether c
(pointer to a char) is big enough to hold 4 chars/bytes. On some platforms
it can be 2 or even 1, hence you're risking to overwrite something else.


I gave the example for my particular machine/hardware just to make it a
point that this might not be a portable code.But apart from that, is it
guaranteed to function as intended where the pointer sizes are 4 bytes
or more.

Also writing past 4 bytes on a machine with 4 byte pointers dosent seem
to affect,though I am aware that undefined behaviour can really be
anything and that could also mean that it dosent manifests itself at
all.But this kind of non-compliant behaviour probably compels people to
write non-portable code in the first place rather than any significant
gain in efficiancy.

Thanks
~
Nov 15 '05 #7
"grid" <pr******@gmail .com> wrote in message
news:Fj******** ****@news.oracl e.com...
The above code is broken. You attempt to store 4 chars/bytes
(1+strlen("abc" )==4) to the variable c, but you don't know whether c
(pointer to a char) is big enough to hold 4 chars/bytes. On some platforms it can be 2 or even 1, hence you're risking to overwrite something else.
I gave the example for my particular machine/hardware just to make it a
point that this might not be a portable code.


It's not portable. It's portable around your machine's hard drive, but not
much further :) Or you should probably ask such portability and undefined
behavior questions at comp.lang.c.x86 or something like that :)
But apart from that, is it
guaranteed to function as intended where the pointer sizes are 4 bytes
or more.
I see no good reason for such code to exist at first place. Perhaps you
could tell me it, if there is.
It's much more easier and portable to declare a local 4-char array. If you
need to use that space either for a pointer or for an array of 4 chars (one
of them at a time), there's a union keyword for that.
Also writing past 4 bytes on a machine with 4 byte pointers dosent seem
to affect,though I am aware that undefined behaviour can really be
anything and that could also mean that it dosent manifests itself at
all.But this kind of non-compliant behaviour probably compels people to
write non-portable code in the first place rather than any significant
gain in efficiancy.


Unportable code is the result of not following the standard (usually not
knowning anything about it and not reading good books that were written with
the standard in mind or not paying attention to those important details) but
instead making own assumptions and relying on something that might or might
not be true. If there's a need for any hardware/CPU-specific code, the
proper way of doing it is to define the API and put portable code on one
side of it and that platform specific code on the other side and never move
a tiny bit of it to the portable part. Unportable code is mixing portable
things with non-portable. Often times those non-portable things are due to
writing say 4 when it must be sizeof(int) or sizeof(int*), improperly
aligning data, improperly calculating sizes of structures and offsets of
their members, reading/writing integers as bytes with big/little endian
problems, ignoring casting to long in multiplication of ints (ignoring the
fact that int and long aren't necessarily types of the same physical size),
etc. The thing is, many books don't mention many practical things and hence
the programmer must invent some way to them, often a quick and durty
non-portable hack.

Alex
Nov 15 '05 #8
grid <pr******@gmail .com> writes:
int main()
{
char *c;
c = &c;
strcpy(c,"abc") ;
puts(&c);
retun 0; }

It should be return 0;
The spell of the return is wrong in the test program above.I did not
have it in my test program which I compiled , but added it while
composing this mail , of the fear of getting battered by the C
language purists ;).


This is why you should *always* copy-and-paste the actual code that
you fed to the compiler, rather than re-typing it.

--
Keith Thompson (The_Other_Keit h) 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 15 '05 #9
Emmanuel Delahaye wrote:
grid wrote on 01/10/05 :
char *c;
c = &c;

Types are incompatible. (c is a char * and &c is a char**)


That is just to make c point to the first byte of the string.We will
anyhow require a cast for this to silence the compiler, since they are
really incompatible types as you mentioned

c = (char *)&c;


The result of the cast is implementation-dependent.


Surely it is defined as producing a pointer to the first byte of c? If
it was *not* (char*), (unsigned char*) or (signed char*) I would agree
with you.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 15 '05 #10

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

Similar topics

2
2927
by: Joona I Palaste | last post by:
AFAIK the C standard divides behaviour of different things into four classes. 1) Defined behaviour. The implementation must do exactly what the standard says. 2) Implementation-defined behaviour. The implementation must choose some behaviour, document it, and be consistent about it. 3) Unspecified behaviour. The implementation must pick one of several possible behaviours, but does not need to be consistent about it. 4) Undefined...
29
2257
by: Enrico `Trippo' Porreca | last post by:
Both K&R book and Steve Summit's tutorial define a getline() function correctly testing the return value of getchar() against EOF. I know that getchar() returns EOF or the character value cast to unsigned char. Since char may be signed (and if so, the return value of getchar() would be outside its range), doesn't the commented line in the following code produce implementation-defined behaviour?
13
2141
by: Chris Croughton | last post by:
Is the following code standard-compliant, and if so what should it do? And where in the standard defines the behaviour? #include <stdio.h> #define DEF defined XXX int main(void) { int defined = 2;
31
2651
by: DeltaOne | last post by:
#include<stdio.h> typedef struct test{ int i; int j; }test; main(){ test var; var.i=10; var.j=20;
8
5665
by: wkaras | last post by:
In my compiler, the following code generates an error: union U { int i; double d; }; U u; int *ip = &u.i; U *up = static_cast<U *>(ip); // error I have to change the cast to reinterpret_cast for the code
9
1802
by: horizon5 | last post by:
Hi, my collegues and I recently held a coding style review. All of the code we produced is used in house on a commerical project. One of the minor issues I raised was the common idiom of specifing: <pre> if len(x) 0: do_something() </pre>
26
2201
by: Frederick Gotham | last post by:
I have a general idea of the different kinds of behaviour described by the C Standard, such as: (1) Well-defined behaviour: int a = 2, b = 3; int c = a + b; (Jist: The code will work perfectly.)
285
9001
by: Sheth Raxit | last post by:
Machine 1 : bash-3.00$ uname -a SunOS <hostname5.10 Generic_118822-30 sun4u sparc SUNW,Sun-Fire-280R bash-3.00$ gcc -v Reading specs from /usr/local/lib/gcc-lib/sparc-sun-solaris2.8/2.95.3/ specs gcc version 2.95.3 20010315 (release)
30
1744
by: Ioannis Vranos | last post by:
AFAIK the following is implementation-defined behaviour, am I right?: #include <stdio.h> int main(void) { int n= 0;
173
14020
by: Ron Ford | last post by:
I'm looking for a freeware c99 compiler for windows. I had intended to use MS's Visual C++ Express and use its C capability. In the past with my MS products, I've simply needed to make .c the filetype to invoke the C compiler. Here's a link http://www.microsoft.com/express/download/#webInstall The download is 2.6 megs, which is near a reasonable size for a compiler, but then setup.exe wants to download 87 megs of dot net framework...
0
9793
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
10774
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...
0
10491
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
10526
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
5617
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5780
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4411
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
3959
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3076
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.