473,943 Members | 23,877 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
31 1402
# 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).

Pointers aren't always four bytes. What you're looking for is
sizeof c>=strlen(strin g)+1

--
SM Ryan http://www.rawbw.com/~wyrmwif/
Death is the worry of the living. The dead, like myself,
only worry about decay and necrophiliacs.
Nov 15 '05 #11
grid wrote:
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 ;).


Let me be the first to warn of impending doom. You define c an object of
type char*. For sake of argument, the compiler arbitrarily places c at
address 0100. Now you assign this address to c itself. If your warnings
are high enough, you will be told about this. c has type char* while &c
has type char**. The two are incompatible types.

Assuming you got away with the assingment 'c = &c;' your c doesn't point
to usable memory. With 'strcpy(c,"abc" );' the Devil steps in, destroying
c and anything else the Devil chooses. You are toast.

Given the prototype in stdio.h as..

int puts(const char *);

What on earth do you think 'puts(&c);' will do?

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 15 '05 #12
In article <QK************ @news.oracle.co m> grid <pr******@gmail .com> wrote:
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<strin g.h>

int main()
{
char *c;
c = &c;
strcpy(c,"abc") ;
puts(&c);
retun 0;
}
This code does not even compile:

% strictcc t.c
t.c: In function `main':
t.c:7: error: assignment from incompatible pointer type
t.c:9: error: passing arg 1 of `puts' from incompatible pointer type
t.c:10: syntax error before `0'
%

Fixing the obvious typo (so that line 10 says "return" instead of
"retun") still gives two error messages and no executable.

Adding the two obvious casts gives a program that fails when run
on some machines -- the "return" does something very bad, since
the bytes beyond &c that were overwritten held the return stack
frame. (Amazingly enough, it *does* work on both the Data General
Eclipse and the Cray, with the casts.)
Can anyone comment if this is compliant code and is the behaviour
guaranteed.


Obviously the answer (to both questions) is "no".
--
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 15 '05 #13
Joe Wright <jw*****@comcas t.net> wrote:
# grid wrote:
# >> int main()
# >> {
# >> char *c;
# >> c = &c;
# >> strcpy(c,"abc") ;
# >> puts(&c);
# >> retun 0; }

# Assuming you got away with the assingment 'c = &c;' your c doesn't point
# to usable memory. With 'strcpy(c,"abc" );' the Devil steps in, destroying

It points to an n-char wide local variable, where n=sizeof c.

# c and anything else the Devil chooses. You are toast.

As long as you copy n-1 or fewer chars (+ null byte terminator),
the only possible risk is if a pointer value in memory, not a
register, can trap to some kind of representation error.

# What on earth do you think 'puts(&c);' will do?

If the pointer value is interpretable as a n-1 (or less)
character string, it would print that string.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
I have no idea what you just said.
I get that alot.
Nov 15 '05 #14
SM Ryan wrote:
Joe Wright <jw*****@comcas t.net> wrote:
# grid wrote:
# >> int main()
# >> {
# >> char *c;
# >> c = &c;
# >> strcpy(c,"abc") ;
# >> puts(&c);
# >> retun 0; }

# Assuming you got away with the assingment 'c = &c;' your c doesn't point
# to usable memory. With 'strcpy(c,"abc" );' the Devil steps in, destroying

It points to an n-char wide local variable, where n=sizeof c.

# c and anything else the Devil chooses. You are toast.

As long as you copy n-1 or fewer chars (+ null byte terminator),
the only possible risk is if a pointer value in memory, not a
register, can trap to some kind of representation error.

# What on earth do you think 'puts(&c);' will do?

If the pointer value is interpretable as a n-1 (or less)
character string, it would print that string.


#include <stdio.h>
#include <string.h>
int main(void) {
char *c;
c = &c;
strcpy(c, "abc");
puts(&c);
return 0;
}

smr.c: In function `main':
smr.c:5: warning: assignment from incompatible pointer type
smr.c:7: warning: passing arg 1 of `puts' from incompatible pointer type

I assume you get similar results. Even if it "works" this is not a
decent program.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 15 '05 #15
Chris Torek wrote:
In article <QK************ @news.oracle.co m> grid <pr******@gmail .com> wrote:
A collegue of mine is of the opinion that the behaviour of the
following program is defined, but I am a little apprehensive.

#include<stdi o.h>
#include<stri ng.h>

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

This code does not even compile:

% strictcc t.c
t.c: In function `main':
t.c:7: error: assignment from incompatible pointer type
t.c:9: error: passing arg 1 of `puts' from incompatible pointer type
t.c:10: syntax error before `0'
%

Fixing the obvious typo (so that line 10 says "return" instead of
"retun") still gives two error messages and no executable.

Adding the two obvious casts gives a program that fails when run
on some machines -- the "return" does something very bad, since
the bytes beyond &c that were overwritten held the return stack
frame. (Amazingly enough, it *does* work on both the Data General
Eclipse and the Cray, with the casts.)

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

Obviously the answer (to both questions) is "no".


I use DJGPP and a batch file to invoke the compiler as..

@echo off
gcc -W -Wall -ansi -pedantic -s -O2 %1.c -o %1.exe -lm

I get the same complaints as you except they are warnings. And there is
an executable produced and it "works" in that it produces

abc

I'm not defending the program, I wonder why I get warnings and you get
errors.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 15 '05 #16
"Joe Wright" <jw*****@comcas t.net> wrote in message
news:I7******** *************** *******@comcast .com...
....
I use DJGPP and a batch file to invoke the compiler as..

@echo off
gcc -W -Wall -ansi -pedantic -s -O2 %1.c -o %1.exe -lm .... I'm not defending the program, I wonder why I get warnings and you get
errors.


There is a command line switch telling the compiler to turn the warnings
into errors, either
-pedantic-errors
or
-Werror
or both will do that -- I've never tried.

Alex
Nov 15 '05 #17
In article <I7************ *************** ***@comcast.com >,
Joe Wright <jw*****@comcas t.net> wrote:
....
I use DJGPP and a batch file to invoke the compiler as..

@echo off
gcc -W -Wall -ansi -pedantic -s -O2 %1.c -o %1.exe -lm

I get the same complaints as you except they are warnings. And there is
an executable produced and it "works" in that it produces

abc

I'm not defending the program, I wonder why I get warnings and you get
errors.


Obviously, because we don't know what's behind Chris's "strictcc" command.

(But I suspect it is an invocation of some C compiler that includes a cmd
line option akin to gcc's "-Werror")

Nov 15 '05 #18
In article <I7************ *************** ***@comcast.com >
Joe Wright <jw*****@comcas t.net> wrote:
[Given a source file for which the C standards require "diagnostic s"
and using DJGPP,] I get the same complaints as you except they are
warnings. And there is an executable produced ... I wonder why I
get warnings and you get errors.


I have a stricter compiler. (Or rather, essentially the same
compiler with some minor gimmicking.)

The C standards say that "a diagnostic" is required, after which
anything may happen. Using "strictcc" I get a diagnostic and no
executable. See also -Werror and/or -pedantic-errors.

(At work, I use both Diab and gcc, which produce somewhat different
sets of warnings. Some code I consider "just fine" produces warnings
with Diab but not with gcc, e.g.:

#define MIN(a, b) ((a) < (b) ? (a) : (b))
...
x = MIN(x, limit);

will draw a warning with Diab under some flags [I have not yet
attempted to determine which ones]. Hence I cannot *always* have
"all warnings treated as errors". It is nice to use "strictcc" or
equivalent for personal projects, though, where I control all
aspects of the project, not just the C source file in question.)
--
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 15 '05 #19
Chris Torek wrote:
grid <pr******@gmail .com> wrote:

#include<stdi o.h>
#include<stri ng.h>

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


This code does not even compile:
Adding the two obvious casts gives a program that fails when run
on some machines -- the "return" does something very bad, since
the bytes beyond &c that were overwritten held the return stack
frame.


How about the 'fixed' version:

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

int main(void)
{
if ( sizeof(char *) >= sizeof "abc" )
{
char *c;
c = (char *)&c;
strcpy(c,"abc") ;
puts(&c);
}
return 0;
}

I think this is always well-defined. It's legal to cast any
object's address to (char *) and that pointer must point to
the object's representation. It's legal to modify memory
that has been allocated by you. This code never actually
evaluates "c" after the strcpy, so the issue of a trap
representation doesn't arise.

Nov 15 '05 #20

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

Similar topics

2
2933
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
2273
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
2146
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
2678
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
5677
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
1811
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
2217
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
9115
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
1775
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
14091
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
10135
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
9970
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
11123
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
11299
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,...
1
8219
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
7390
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6087
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...
1
4910
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
4510
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.