473,789 Members | 2,598 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Query on pointers

What's wrong with this program? If you were to fix it, what would the
intended output be?

void swap(char *str, int index1, int index2) {
char tmp = str[index1];
str[index1] = str[index2];
str[index2] = tmp;
}

int main(int argc, char *argv[]) {
char *planet1;
char *planet2;

planet1 = (char *) malloc(7 * sizeof(char));
if (!planet1)
return 0;

snprintf(planet 1, 7, "Jupiter");
planet2 = "Saturn";

swap(planet1, 0, 3);
swap(planet2, 3, 4);

printf("results : %s and %s\n", planet1, planet2);
return 0;
}

My interpretation : In turboc3 compiler(though it is a dead compiler
now) this problem is perfectly fine and we
get the o/p :

results: iupJter and Satrun

But in Bloodshed Dev C++ the code compiles fine but on
execution there is an error report generated.

swap(planet1,0, 3) works fine but there is some problem
with swap(planet2,3, 4)

Only when i allocate space for planet2 and perform
snprintf on planet2 i get the expected result.

Why do we need snprintf in this case....why does
planet2="Saturn " not work?

PS:Pls send your comments and correct me if i am wrong...i am working
on this problem for 2 long days.

May 4 '07
16 1552
ma**********@po box.com wrote:
On 4 May, 15:23, Kenneth Brody <kenbr...@spamc op.netwrote:
>Also, your 7-byte buffer for the 8-byte string "Jupiter" (with the
'\0' terminator) "works" only by luck. The runtime library is
probably allocating more than 7 bytes, in order to handle proper
alignment, so you happen to have additional memory after your 7
bytes, and the 8th byte happens to be zero. Otherwise, the final
printf() wouldn't have stopped after the 7 characters "iupJter".
It would have kept going until it hit a '\0' or crashed.

I think, indeed I'm fairly sure, you are mistaken.

The snprintf() call will move "Jupite" into the buffer allocated,
and then add the null character to make it a legal C string.

Either the original poster is mistaken about the output from turboc,
or it's broken.
It probably worked because malloc allocated a multiple of 8 (or 4)
bytes. No guarantees.

And no, the snprintf doesn't know the size of the buffer. All it
has is what you tell it, and pointers to the buffer beginning. It
wasn't designed to handle strings.

--
<http://www.cs.auckland .ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfoc us.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>
<http://kadaitcha.cx/vista/dogsbreakfast/index.html>
cbfalconer at maineline dot net

--
Posted via a free Usenet account from http://www.teranews.com

May 4 '07 #11
Ajinkya wrote:
On May 4, 10:13 am, Bart van Ingen Schenau <b...@ingen.ddn s.info>
wrote:
>ak wrote:
Check it on any "decent" compiler snprintf() moves "Jupiter" and
not "Jupite" ....i think you are mistaken.

Then you have a strange notion of 'decent compiler'.
Any *conforming* implementation, will truncate the string to
"Jupite", as that is what the standard requires for snprintf().

Bart v Ingen Schenau

wont you call Bloodshed Dev C++ a "decent" compiler....... i know
ideally any compiler should not do it but all the compilers i have do
it("Jupiter")
I call it a non-conforming (C99) implementation.
Which does not surprise me, because to my knowledge, it does not claim
conformance to C99.

Whether it is a "decent" implementation, depends on how it copes with
things like this:

* * char planet1[7];
* * snprintf(planet 1, 7, "Jupiter (The big red planet in our solar
system)");

Bart v Ingen Schenau
--
a.c.l.l.c-c++ FAQ: http://www.comeaucomputing.com/learn/faq
c.l.c FAQ: http://www.eskimo.com/~scs/C-faq/top.html
c.l.c++ FAQ: http://www.parashift.com/c++-faq-lite/
May 6 '07 #12
Bart van Ingen Schenau said:

<snip>
Whether it is a "decent" implementation, depends on how it copes with
things like this:

char planet1[7];
snprintf(planet 1, 7, "Jupiter (The big red planet in our solar
system)");
This is rather like judging whether a Formula One car is "decent" by
smacking it into the wall at 200mph to see if the air-bag goes off.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
May 6 '07 #13
ma**********@po box.com wrote:
>
On 4 May, 15:23, Kenneth Brody <kenbr...@spamc op.netwrote:
Also, your 7-byte buffer for the 8-byte string "Jupiter" (with the
'\0' terminator) "works" only by luck. The runtime library is
probably allocating more than 7 bytes, in order to handle proper
alignment, so you happen to have additional memory after your 7
bytes, and the 8th byte happens to be zero. Otherwise, the final
printf() wouldn't have stopped after the 7 characters "iupJter".
It would have kept going until it hit a '\0' or crashed.

I think, indeed I'm fairly sure, you are mistaken.

The snprintf() call will move "Jupite" into the buffer allocated, and
then add the null character to make it a legal C string.

Either the original poster is mistaken about the output from turboc,
or it's broken.
Well, some further investigation shows that the FreeBSD man pages say:

The snprintf() and vsnprintf() functions will write at most size-1
of the characters printed into the output string (the size'th
character then gets the terminating `\0'); [...] The output is
always null-terminated.

It also says that snprintf() is C99.

My C90 implementation doesn't even have snprintf(). However, it does
have an _snprintf(), which says:

The _snprintf function formats and stores count or fewer characters
and values (including a terminating null character that is always
appended unless count is zero or the formatted string length is
greater than or equal to count characters) in buffer.

So, it appears that a C99 implementation would put "Jupite". However,
a pre-C99 implementation is not required to do so. Given the fact
that the OP said the output included the 'r' in "iupJter", my guess is
that it is not a C99 implementation, and is not nul-terminating the
string.

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer .h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>

May 6 '07 #14
On May 5, 1:28 am, ajinkya.c...@gm ail.com wrote:
What's wrong with this program? If you were to fix it, what would the
intended output be?
Slightly strange question, as who can know the intended output
except for the person who wrote it?
planet1 = (char *) malloc(7 * sizeof(char));
snprintf(planet 1, 7, "Jupiter");
Something nobody has mentioned yet: you failed to write:
#include <stdlib.h>
#include <stdio.h>

so the above lines cause undefined behaviour.

(Sometimes it can be assumed that these includes were omitted
for brevity, but I don't feel confident the OP knows that these lines
are required).

May 6 '07 #15
On May 5, 1:58 am, mark_blue...@po box.com wrote:
On 4 May, 14:28, ajinkya.c...@gm ail.com wrote:
If you were to fix it, what would the intended output be?

I don't know. It's not my program.
planet1 = (char *) malloc(7 * sizeof(char));
if (!planet1)
return 0;
snprintf(planet 1, 7, "Jupiter");

Why you felt the need to use snprintf() rather than strcpy(), or
strncpy(), I can't imagine.
I'm surprised that multiple people made this comment. strcpy
and strncpy would both cause the program to have undefined
behaviour (assuming appropriate headers are included in
all cases, that is).

As it is, snprintf will not cause UB. Conceivably the result is
not the inteded one -- but as you pointed out, we can't know
what the intended result even was.

May 6 '07 #16
Old Wolf said:
On May 5, 1:58 am, mark_blue...@po box.com wrote:
>On 4 May, 14:28, ajinkya.c...@gm ail.com wrote:
planet1 = (char *) malloc(7 * sizeof(char));
if (!planet1)
return 0;
snprintf(planet 1, 7, "Jupiter");

Why you felt the need to use snprintf() rather than strcpy(), or
strncpy(), I can't imagine.

I'm surprised that multiple people made this comment. strcpy
and strncpy would both cause the program to have undefined
behaviour (assuming appropriate headers are included in
all cases, that is).
Never mind strcpy, strncpy, and snprintf - why he felt the need to use
malloc is beyond me. Simple arrays of char would have done the trick.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
May 6 '07 #17

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

Similar topics

4
8977
by: Starbuck | last post by:
OK, first let me say that I am no DB person. But I have a user here who keeps getting this error whenever she does, whatever it is she does, with databases... A google search takes me to various forums where I am forced to sign up before I can read any answers. Interesting note here is that the guy in the office next
5
1347
by: Alexander Korovyev | last post by:
Suppose I have two tables: CREATE TABLE Tab1 ( NOT NULL, NOT NULL, NOT NULL, NOT NULL) CREATE TABLE Tab2 ( NOT NULL,
11
3478
by: Bradford Chamberlain | last post by:
I work a lot with multidimensional arrays of dynamic size in C, implementing them using a single-dimensional C array and the appropriate multipliers and offsets to index into it appropriately. I tend to iterate over subsets of these arrays by walking a pointer and an offset per dimension across their dimensions. I've found that this tends to result in more performance in a portable manner than doing explicit indexing calculations and...
2
2875
by: Jean | last post by:
Hello everyone, I was having the following problem with a query, and after failing to find a similar solution on these newsgroups I decided to post here. I am quite new to Access, so would appreciate any help/pointers in the right direction. The problem is that I keep getting the error to the likes of "Data types in the criterion expression are incompatible" when the query runs.
19
1633
by: s.subbarayan | last post by:
Dear all, I had this following doubt,while java is able to carryon with out pointers why C language cant be modified to remove pointer?Hows java able to do this with out pointers? I jus plead sorry to those who advice me to post it to java people because I have already done it. Jus want to know alternatives to pointers which can be used with C.While pointers provide flexibility most bugs are with respect to pointers.So will it not be...
0
1194
by: Simon Devlin | last post by:
Ok, I realize that this is vague, but I'm stuck :-( I've a particular query that when executed from within asp.net times out (after 30 seconds) If I do it from within the SQL Query Analyzer on the same machine, it works fine (and in general takes < 2 seconds) It's possible that it's connection pool exhaustion - the message that comes up is the usual "timeout. maybe connection could not be allocated...blah...blah", but if I kill the...
1
2017
by: Peter Alberer | last post by:
Hi there, i have a problem with a query that uses the result of a plsql function In the where clause: SELECT assignments.assignment_id, assignments.package_id AS package_id, assignments.title AS title, COUNT(*) AS Count
2
1480
by: Alan | last post by:
I'm having a bit of difficulty getting the results I need from our database. In a nutshell I'm trying to work out trends in what people buy next. So, for example, I'm trying to run a query that extracts all orders containing product1 and then trying to run another query that gives me a count on products purchased AFTER that product was purchased. My table relationships are fairy standard for an order processing database: Customer...
1
1379
by: bolabala | last post by:
Hello All, A small query regarding function pointers, I just want to know whether it is possible to store functions having different prototypes in an array of function pointers. I know that an array of function pointers can contain functions of the same prototype but want to know if by other means i can able to access these functions (having different prototype) using an array indirection. ...
14
2134
by: gert | last post by:
Why does query = www ? int main(void) { char *user="www"; char *password=""; char *database="www"; char *query={"SHOW DATABASES;"}; db(user,password,database,query);
0
9663
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
10404
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
10195
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
10136
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
9979
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...
0
9016
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7525
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
6765
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
5548
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.