473,776 Members | 1,650 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 #1
16 1551
aj**********@gm ail.com wrote:
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));
"Jupiter" is 7 characters, so you must allocate 8. Why? You figure it out...

if (!planet1)
return 0;

snprintf(planet 1, 7, "Jupiter");
Use strcpy().

planet2 = "Saturn";
Here planet2 points to a string literal, which in most cases is
non-modifiable.
..
>
swap(planet1, 0, 3);
swap(planet2, 3, 4);
And here you write to planet2. That's not a good idea, as you discovered.
HTH
Bjørn
[snip]
May 4 '07 #2
On 4 May, 14:28, ajinkya.c...@gm ail.com wrote:
What's wrong with this program?
It's broken...
If you were to fix it, what would the intended output be?
I don't know. It's not my program.
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));
I would suggest that you don't cast the result of malloc - use
<stdlib.h- see FAQ http://c-faq.com/malloc/mallocnocast.html.

sizeof(char) is by definition, I believe, 1, so it served no purpose.

You've allocated 7 characters for planet1.
if (!planet1)
return 0;

snprintf(planet 1, 7, "Jupiter");
"Jupiter" is not actually 7 characters long, is it? The result in the
space pointed to by planet1 will be "Jupite" (plus the obligatory
trailing '\0';

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

If you use snprintf(), shouldn't you include <stdio.h>?
planet2 = "Saturn";
planet2 points to data which may well be read-only...
swap(planet1, 0, 3);
This will swap the "J" and "i" in "Jupite".
swap(planet2, 3, 4);
On my system, as I'd expected, this crashes with segmentation
violation, as you try to modify data in read-only memory.
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
Really? turboc3 is broken in that case, as the 1st planet cannot
legitimately be "Jupiter" ...
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?
See my comments above on read-only memory.

May 4 '07 #3
aj**********@gm ail.com wrote:
What's wrong with this program? If you were to fix it, what would the
intended output be?
Whatever the redesigned program was written to output.

It is obviously wrong to omit
#include <stdlib.h>
#include <stdio.h>
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));
The cast is unnecessay and bad programming practice.
sizeof(char) is by definition 1.
If you want no more flexibility than your code,
planet1 = malloc(7);
The magic number '7' is a bad idea, of course.
if (!planet1)
return 0;

snprintf(planet 1, 7, "Jupiter");
planet2 = "Saturn";
Replace all of the above with
char planet1[] = "Jupiter";
char planet2[] = "Saturn";
>
swap(planet1, 0, 3);
swap(planet2, 3, 4);
You have just tried to modify a string literal. This is a very bad idea
and has unpredicatable consequences. One possible one is a program
crash. If you replace all of the code in main before the swap with the
two lines I suggested, this problem will not arise.
>
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
That TurboC allowed you to get away with this is just bad luck. It
would have been better for you if your program has crashed.
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.
Because you foolishly try to modify a string literal.
>
swap(planet1,0, 3) works fine but there is some problem
with swap(planet2,3, 4)
No kidding.
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?
You don't need snprintf(). In addition to my suggested replacement
above, any of strcpy, memcpy, memmove, and sprintf could have been used.
There are other choices as well.
planet2 = "Saturn";
*does* work. It points planet2 to a string literal. It is you attempt
to modify the string literal that fails.
>
PS:Pls send your comments and correct me if i am wrong...i am working
on this problem for 2 long days.
You could have just checked the FAQ articles on the difference between
pointers and arrays in minutes, or even (horrors) read your textbook,
preventing the waste of 2 long days.
May 4 '07 #4
aj**********@gm ail.com wrote:
>
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;
}
Question: What should the final printf() do with planet1, which
was allocated 7 bytes, all of which were filled with something
other than '\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
You got (un)lucky in that it gave the results you expected, rather
than crashing.
But in Bloodshed Dev C++ the code compiles fine but on
execution there is an error report generated.
It found the errors that TurboC3 failed to crash on.
swap(planet1,0, 3) works fine but there is some problem
with swap(planet2,3, 4)
planet2 is a pointer to a string literal, which may be placed in
read-only memory.
Only when i allocate space for planet2 and perform
snprintf on planet2 i get the expected result.
By making that change, you have guaranteed that the memory it points
to is writable. (Assuming that malloc worked, of course.)
Why do we need snprintf in this case....why does
planet2="Saturn " not work?
See above. The string "Saturn" can be placed in read-only memory.
PS:Pls send your comments and correct me if i am wrong...i am working
on this problem for 2 long days.
Who is "Pls"?

The ancient turboc3 compiler (16-bit real mode?) didn't place the
string literal into read-only memory. (There was no such thing in
the x86's "real mode" memory scheme, unless it was something like
ROM.) The Bloodshed Dev C++ complier probably runs in "protected
mode" on the x86 CPU, allowing it to place code and data in read-
only memory.

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.

--
+-------------------------+--------------------+-----------------------+
| 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 4 '07 #5
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.

May 4 '07 #6
ak
On May 4, 7:36 am, mark_blue...@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.
Check it on any "decent" compiler snprintf() moves "Jupiter" and not
"Jupite" ....i think you are mistaken.
May 4 '07 #7
ak <aj**********@g mail.comwrote:
>Check it on any "decent" compiler snprintf() moves "Jupiter" and not
"Jupite" ....i think you are mistaken.
#include <stdio.h>

int main(void)
{
char s[10];
snprintf(s, 7, "%s", "Jupiter");
printf("\"%s\"\ n", s);
return 0;
}

$ cc --version
cc (GCC) 3.4.6

$ foo
"Jupite"

C99 7.19.6.5p2, The snprintf Function:
# output characters beyond the n-1st are discarded rather than being
# written to the array, and a null character is written at the end of
# the characters actually written into the array.

-Beej

May 4 '07 #8
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
--
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 4 '07 #9
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
--
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/
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")
May 4 '07 #10

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

Similar topics

4
8975
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
3477
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
1632
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
1378
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
9628
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
9464
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
10292
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
10122
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
10061
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
6722
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
5368
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...
2
3627
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2860
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.