473,545 Members | 2,679 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

doubt regarding pointer assignment

Hi All,

I have a doubt regarding the pointer assignment . Please have a look
at the following program .

#include<stdio. h>
#include<stdlib .h>
#define NAMESIZE 10
#define SAFE_FREE(t) if(t)\
{\
free(t);\
t=NULL;\
}\

int main(void)
{

char *s = malloc(NAMESIZE * sizeof *s);
s = "somenath";
*(s+1)= 'b';/* will it show undefine behavior ??*/
puts(s);
SAFE_FREE(s);
return 0;
}

My question is
1) is the assignment "s = "somenath"; " copy the string to s?
2) is the behavior of *(s+1)= 'b' is defined ?
Currently I am getting the output as

sbmenath
Regards,
Somenath

Aug 30 '07 #1
8 2023
somenath said:
Hi All,

I have a doubt regarding the pointer assignment .
More idiomatically, "I have a question regarding pointer assignment."
(Strike two.)
Please have a look
at the following program .

#include<stdio. h>
#include<stdlib .h>
#define NAMESIZE 10
#define SAFE_FREE(t) if(t)\
{\
free(t);\
t=NULL;\
}\
What makes you think this macro justifies its name?
int main(void)
{

char *s = malloc(NAMESIZE * sizeof *s);
That's fine.
s = "somenath";
That isn't. You just leaked memory. What you intended to do was to copy
the string literal "somenath" into the buffer allocated by malloc,
whose first byte's address is stored in s. To do this, #include
<string.hand use strcpy to copy the string into the buffer, provided
of course that s != NULL.
*(s+1)= 'b';/* will it show undefine behavior ??*/
Yes as your code stands, but not if you correct it as I outlined above.
puts(s);
SAFE_FREE(s);
return 0;
}

My question is
1) is the assignment "s = "somenath"; " copy the string to s?
No. The string literal "somenath" resides at some address or other, and
the assignment simply stores that address in s (which necessarily means
that s can no longer store the address of the block that may have been
allocated by malloc). No copying of the string has occurred.
2) is the behavior of *(s+1)= 'b' is defined ?
Not in your code as written.
Currently I am getting the output as

sbmenath
One of the possible outcomes of undefined behaviour is "what you hoped
would happen", but it is by no means the only one.

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Aug 30 '07 #2
On Aug 30, 10:46 am, somenath <somenath...@gm ail.comwrote:
Hi All,

I have a doubt regarding the pointer assignment . Please have a look
at the following program .

#include<stdio. h>
#include<stdlib .h>
#define NAMESIZE 10
#define SAFE_FREE(t) if(t)\
{\
free(t);\
t=NULL;\
}\

int main(void)
{

char *s = malloc(NAMESIZE * sizeof *s);
s = "somenath";
*(s+1)= 'b';/* will it show undefine behavior ??*/
puts(s);
SAFE_FREE(s);
return 0;

}

My question is
1) is the assignment "s = "somenath"; " copy the string to s?
2) is the behavior of *(s+1)= 'b' is defined ?
Currently I am getting the output as

sbmenath

Regards,
Somenath
You are doing smething really nasty.

The line
s = "somenath"
actually replaces the pointer to the allocated memory references by
's' with the pointer to a static method variable.
Then you are modifying static data!

You should have done
strcpy(s, "somenath);

And the behaviour will be defined.

Mariano.

Aug 30 '07 #3
at the following program .
>
#include<stdio. h>
#include<stdlib .h>
#define NAMESIZE 10
#define SAFE_FREE(t) if(t)\
{\
free(t);\
t=NULL;\
}\

What makes you think this macro justifies its name?
Thanks for the information. By using this macro I wanted to avoid the
repetation of following steps
1)Before freeing pointer check if it is NULL.
2)If not NULL free it .
3)After freeing assign the pointer to NULL.
I think i am achieving these by the macro SAFE_FREE.
Please provide your inputs if it is not doing so. or what i am doing
wrong or how it can cause problem or it can be improved .

Thanks

Regards,
Somenath

Aug 30 '07 #4
somenath wrote:
I have a doubt regarding the pointer assignment . Please have a look
at the following program .

#include<stdio. h>
#include<stdlib .h>
#define NAMESIZE 10
#define SAFE_FREE(t) if(t)\
{\
free(t);\
t=NULL;\
}\
Horrible horrible. If you /are/ going to tempt fate this way,
what's wrong with:

#define SAFE_FREE(t) (free( t ), t = NULL)

which at least is short and doesn't lead you into a semicolon
trap.

[There are at least two ways which make this a fate-tempting
macro, one more subtle than the other.]
int main(void)
{

char *s = malloc(NAMESIZE * sizeof *s);
s = "somenath";
Oops. You've just lost your reference to the allocated store.

Perhaps you meant

strcpy( s, "somenath" );

?
*(s+1)= 'b';/* will it show undefine behavior ??*/
[Why not write this as

s[1] = 'b';
?]

As you have written it, yes, because you're trying to change
the second character of the string literal, and this is Not
Allowed.
puts(s);
SAFE_FREE(s);
That's the semicolon trap: there's an empty statement between
the `)` and the `;`. Think about what would happen if the
SAFE_FREE was the then-part of an `if` with an `else`.
return 0;
My question is
1) is the assignment "s = "somenath"; " copy the string to s?
No.
2) is the behavior of *(s+1)= 'b' is defined ?
Not as written.
Currently I am getting the output as

sbmenath
It appears your implementation doesn't take advantage of its permission
to store string literals in read-only memory.

--
Chris "pointing not holding" Dollin

Hewlett-Packard Limited registered office: Cain Road, Bracknell,
registered no: 690597 England Berks RG12 1HN

Aug 30 '07 #5
Richard Heathfield <rj*@see.sig.in validwrites:
somenath said:
>Hi All,

I have a doubt regarding the pointer assignment .

More idiomatically, "I have a question regarding pointer assignment."
(Strike two.)

1
>
>Please have a look
at the following program .

#include<stdio .h>
#include<stdli b.h>
#define NAMESIZE 10
#define SAFE_FREE(t) if(t)\
{\
free(t);\
t=NULL;\
}\

What makes you think this macro justifies its name?
2

So two answers. 2 picky, trite little comments with no correction and/or
actual advice. This is the kind of pedantry and rudeness so often
mentioned in relation to this group. If you are going to pick on such
issues then have the god given good grace to explain why you are so
pleased with yourself. The OP might learn something.

>int main(void)
{

char *s = malloc(NAMESIZE * sizeof *s);

That's fine.
> s = "somenath";

That isn't. You just leaked memory. What you intended to do was to copy
the string literal "somenath" into the buffer allocated by malloc,
whose first byte's address is stored in s. To do this, #include
<string.hand use strcpy to copy the string into the buffer, provided
of course that s != NULL.
> *(s+1)= 'b';/* will it show undefine behavior ??*/

Yes as your code stands, but not if you correct it as I outlined
above.
RH means something like

strcpy(s,"somen ath");
>
> puts(s);
SAFE_FREE(s);
return 0;
}

My question is
1) is the assignment "s = "somenath"; " copy the string to s?

No. The string literal "somenath" resides at some address or other, and
the assignment simply stores that address in s (which necessarily means
that s can no longer store the address of the block that may have been
allocated by malloc). No copying of the string has occurred.
>2) is the behavior of *(s+1)= 'b' is defined ?

Not in your code as written.
Yes is if s points to a valid string. Which it does before you
mistakenly set it to point to "somenath".
>
>Currently I am getting the output as

sbmenath

One of the possible outcomes of undefined behaviour is "what you hoped
would happen", but it is by no means the only one.
You output is what would be expect in 99.99% of cases and is probably
what you expected it to be. It is however "undefined" in that you did
not store the 'b' in your malloced memory, rather in the "static" string
area used to store "somenath".
Aug 30 '07 #6
Richard <rg****@gmail.c omwrites:
Richard Heathfield <rj*@see.sig.in validwrites:
>somenath said:
[...]
>>2) is the behavior of *(s+1)= 'b' is defined ?

Not in your code as written.

Yes is if s points to a valid string. Which it does before you
mistakenly set it to point to "somenath".
>>
>>Currently I am getting the output as

sbmenath

One of the possible outcomes of undefined behaviour is "what you hoped
would happen", but it is by no means the only one.

You output is what would be expect in 99.99% of cases and is probably
what you expected it to be. It is however "undefined" in that you did
not store the 'b' in your malloced memory, rather in the "static" string
area used to store "somenath".
Really? When I compiled and ran the program, I got the output I
expected, namely:

Segmentation fault (core dumped)

String literals are very commonly stored in read-only memory (not
necessarily physically read-only except on embedded systems, but in a
memory segment that's protected from writing by the operating system).

The output the OP got, "sbmenath", is not surprising (apparently his
system doesn't write-protect string literals), but some kind of
program crash is also very likely.

--
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."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 30 '07 #7
somenath wrote:
>
I have a doubt regarding the pointer assignment . Please have a
look at the following program .

#include<stdio. h>
#include<stdlib .h>
#define NAMESIZE 10
#define SAFE_FREE(t) if(t)\
{\
free(t);\
t=NULL;\
}\
Silly macro. "free(NULL) " is treated as a NOP. See the standard.
>
int main(void) {
char *s = malloc(NAMESIZE * sizeof *s);
s = "somenath";
destroying s value and making a memory leak.
*(s+1)= 'b';/* will it show undefine behavior ??*/
and now pointing to a non-modifiable char const. Boom. Undefined
behaviour.
puts(s);
SAFE_FREE(s);
return 0;
}

My question is
1) is the assignment "s = "somenath"; " copy the string to s?
2) is the behavior of *(s+1)= 'b' is defined ?
You are asking the wrong questions. But the answers are no, yes.
Note that s can't hold a string, only a pointer.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

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

Aug 30 '07 #8
somenath wrote:
>
Hi All,

I have a doubt regarding the pointer assignment . Please have a look
at the following program .

#include<stdio. h>
#include<stdlib .h>
#define NAMESIZE 10
#define SAFE_FREE(t) if(t)\
{\
free(t);\
t=NULL;\
}\

int main(void)
{

char *s = malloc(NAMESIZE * sizeof *s);
s = "somenath";
*(s+1)= 'b';/* will it show undefine behavior ??*/
puts(s);
SAFE_FREE(s);
return 0;

}

My question is
1) is the assignment "s = "somenath"; " copy the string to s?
No.
2) is the behavior of *(s+1)= 'b' is defined ?
No.
Currently I am getting the output as

sbmenath
Sheer luck.

/* BEGIN new.c */

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

#define STRING "somenath"

int main(void)
{
char *s = malloc(sizeof STRING);

if (s == NULL) {
puts("s == NULL");
exit(EXIT_FAILU RE);
}
strcpy(s, STRING);
s[1]= 'b';
puts(s);
free(s);
s = NULL;
return 0;
}

/* END new.c */
--
pete
Aug 31 '07 #9

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

Similar topics

138
5137
by: ambika | last post by:
Hello, Am not very good with pointers in C,but I have a small doubt about the way these pointers work.. We all know that in an array say x,x is gonna point to the first element in that array(i.e)it will have the address of the first element.In the the program below am not able to increment the value stored in x,which is the address of...
2
4158
by: Arun Prasath | last post by:
Hi all, I have the following question regd pointer typecasting. Is the following type of pointer typecasting valid? #define ALLOC(type,num) ((type *)malloc(sizeof(type)*num)) /*begin code*/
22
3121
by: srivatsan_b | last post by:
Hi, Can somebody explain whether an explicit typecast is mandatory while calling memset function for a structure? like in the following code snapshot..... struct some_structure x; memset((some_structure*)&x,0,sizeof(some_structure)); Will memset(&x,0,sizeof(some_structure)); cause some issues? Thanks in advance
9
10135
by: kiran.agashe | last post by:
Hi, Please refer program below: #include <string> #include <cstdio> using namespace std; const char* f(); main() {
8
2387
by: toton | last post by:
HI, One more small doubt from today's mail. I have certain function which returns a pointer (sometimes a const pointer from a const member function). And certain member function needs reference (or better a const reference). for eg, const PointRange* points = cc.points(ptAligned);
33
5020
by: Ney André de Mello Zunino | last post by:
Hello. I have written a simple reference-counting smart pointer class template called RefCountPtr<T>. It works in conjunction with another class, ReferenceCountable, which is responsible for the actual counting. Here is the latter's definition: // --- Begin ReferenceCountable.h ---------- class ReferenceCountable
6
2137
by: reji_thomas | last post by:
Hi, I have a doubt in the following code: struct xyz { int x; long l; float f; };
2
35508
weaknessforcats
by: weaknessforcats | last post by:
Handle Classes Handle classes, also called Envelope or Cheshire Cat classes, are part of the Bridge design pattern. The objective of the Bridge pattern is to separate the abstraction from the implementation so the two can vary independently. Handle classes usually contain a pointer to the object implementation. The Handle object is used...
4
1726
by: Deep | last post by:
I'm in doubt about what is smart pointer. so, please give me simple description about smart pointer and an example of that. I'm just novice in c++. regards, John.
0
7496
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...
0
7428
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...
0
7784
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...
0
6014
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...
0
5071
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...
0
3485
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...
1
1916
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
1
1039
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
738
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...

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.