reassigning value of a pointer

  • Follow


Hi all,

In the following code I am trying to change the contents of a string:

int main()
{
  char *string="testing";
  rename(string);

  return 0;
}

void rename(char *s)
{
  printf("Character 1: %c\n",*s);
  *s='a';
  printf("Character 1 now: %c\n",*c);
}

Anyway, I am sure this is possible but for some reason I'm getting
segmentation faults at line *s='a'; when I attempt to change the value
in which *s is currently pointing to, being the first character in the
string.

Any ideas?

Thanks in advance,

Ben.

0
Reply bhalicki (29) 9/28/2005 4:12:29 AM

In article <1127880749.055321.196690@g14g2000cwa.googlegroups.com>,
 <bhalicki@dodo.com.au> wrote:
>In the following code I am trying to change the contents of a string:

>int main()
>{
>  char *string="testing";

The standard allows string literals to be stored in read-only memory.
An assignment of a string literal to a pointer sets the pointer value
to the address of that {possibly read-only} memory.

In particular,  char *string="testing"; usually does not allocate some
memory somewhere and copy the string into it at runtime. That's
one of the possible behaviours, but it isn't the only possible
behaviour.

Another thing to note is that it is allowed for the compiler
to merge all string literals -- so for example if you also had

  char *anotherstring="testing";

then anotherstring could end up as the same pointer value as
your string variable. Furthermore, if you had

  char *thirdstring="just testing";

then string and anotherstring could end up pointing at the terminal
"testing" substring of the "just testing".

If you need a modifiable string, allocate the memory (somehow) and
copy the appropriate contents into it.
-- 
  "It is important to remember that when it comes to law, computers
  never make copies, only human beings make copies.  Computers are given
  commands, not permission. Only people can be given permission."
                                               -- Brad Templeton
0
Reply roberson2 (8067) 9/28/2005 4:49:26 AM


Thanks for that information Walter.  I managed to get it working, by
allocating the memory then using strcpy to load the string.

Regards,

Ben.

0
Reply bhalicki (29) 9/28/2005 5:31:22 AM

bhalicki@dodo.com.au wrote:
> Hi all,
> 
> In the following code I am trying to change the contents of a string:

Then don't use string literals.

> 
> int main()
> {
>   char *string="testing";

If you want to change the string, don't make 'string' point to a literal 
constant; use an array:
    char string[] = "testing";

Always check the FAQ before posting.  In this case, you might have found
<http://www.eskimo.com/~scs/C-faq/q1.32.html> useful.
0
Reply mambuhl (2201) 9/28/2005 6:15:57 AM

in the above program what is "c", not declared in the program, first u
declare that and assign a value and then print it ok.  i think that
there is no problem in the line *s='a';
so try it and send me the result.

0
Reply hemalatha.gopalakrishnan (1) 9/28/2005 6:28:19 AM

Martin Ambuhl wrote:

> Then don't use string literals.

> If you want to change the string,
> don't make 'string' point to a literal constant;

There is no such thing as a "literal constant" in C.

>     char string[] = "testing";

You just used a string literal to initialize an array.

-- 
pete
0
Reply pfiland (6614) 9/28/2005 6:34:39 AM

bhalicki@dodo.com.au wrote:

> int main()
> {
>   char *string="testing";
>   rename(string);

Your immediate problem is as others have explained it. However, you have
another bug: rename() is already a Standard function, and you cannot
redefine it, let alone redefine it with an incompatible declaration.

Richard
0
Reply rlb (4118) 9/28/2005 7:04:15 AM

It becomes a standard function iff (if and only if) you include
<stdio.h>. Although dubbed as *Standard* Input Ouput - not really a
standard. Any programmer could redefine functions already defined in
*Standard* headers. Other than that, what the original author intended
to do clearly shouldn't be named as rename(..); rather,
change_sptr(...); Or something simliar.

0
Reply kioria (6) 9/28/2005 9:13:26 AM

David G. Hong wrote:
> 
> It becomes a standard function iff (if and only if) you include
> <stdio.h>. 

How do you figure that?

N869
      7.1.3  Reserved identifiers
       [#1]
         -- All  identifiers  with  external  linkage in any of the
            following  subclauses  (including  the  future  library
            directions)  are always reserved for use as identifiers
            with external linkage.

-- 
pete
0
Reply pfiland (6614) 9/28/2005 9:41:11 AM

David G. Hong wrote:

Provide context. This is possible and instructions were posted only 
yesterday, so had you read the group before posting (you should always 
read a few days posts before your first post to a group) you would have 
know to do this and *how* to do it. It's something like pressing the 
"options" button and using the reply button that provides.

> It becomes a standard function iff (if and only if) you include
> <stdio.h>. Although dubbed as *Standard* Input Ouput - not really a
> standard. Any programmer could redefine functions already defined in
> *Standard* headers.

Wrong. The standard does not allow you to redefine *any* of the standard 
functions whether you include the relevant header or not. *Some* 
implementations allow you to do this and define the behaviour, but it is 
not portable.

 > Other than that, what the original author intended
> to do clearly shouldn't be named as rename(..); rather,
> change_sptr(...); Or something simliar.

Well, since you've not provided any context it is hard to tell what a 
sensible name would be.
-- 
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
0
Reply spam331 (4024) 9/28/2005 10:44:16 AM

On Wed, 28 Sep 2005 06:34:39 +0000, pete wrote:

> Martin Ambuhl wrote:
> 
>> Then don't use string literals.
> 
>> If you want to change the string,
>> don't make 'string' point to a literal constant;
> 
> There is no such thing as a "literal constant" in C.

It is a resonable description of a string literal object.

>>     char string[] = "testing";
> 
> You just used a string literal to initialize an array.

which solves the primary problem in the original code. I'm not clear what
point you are trying to make here.

Lawrence

0
Reply lknews (877) 9/28/2005 12:21:19 PM

Lawrence Kirby wrote:
> 
> On Wed, 28 Sep 2005 06:34:39 +0000, pete wrote:
> 
> > Martin Ambuhl wrote:
> >
> >> Then don't use string literals.

> > You just used a string literal
 
> which solves the primary problem in the original code.
> I'm not clear what
> point you are trying to make here.

He said not to use string literals 
and then he used one.

-- 
pete
0
Reply pfiland (6614) 9/28/2005 2:58:04 PM

Lawrence Kirby wrote:
> 
> On Wed, 28 Sep 2005 06:34:39 +0000, pete wrote:

> > There is no such thing as a "literal constant" in C.
> 
> It is a resonable description of a string literal object.

The standard lists many types of constants.
No objects are constants.

As used in a pointer initialization,
a string literal converts to an "address constant",
which would have been a better term to use.

-- 
pete
0
Reply pfiland (6614) 9/28/2005 3:12:19 PM

bhalicki@dodo.com.au wrote:

> Thanks for that information Walter.  I managed to get it working, by
> allocating the memory then using strcpy to load the string.


Please read my sig.



Brian

-- 
Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header.
0
Reply defaultuserbr (3657) 9/28/2005 4:00:40 PM

On 28 Sep 2005 02:13:26 -0700, in comp.lang.c , "David G. Hong"
<kioria@gmail.com> wrote:

>It becomes a standard function iff (if and only if) you include
><stdio.h>. 

This is incorrect. What you're referring to is the fact that if you
don't include the header, the compiler may not complain about an
incompatible definition. 

>Although dubbed as *Standard* Input Ouput - not really a
>standard. 

Actually, they are - in order for a C compiler to be
Standard-compliant, it must provide these functions.

>Any programmer could redefine functions already defined in
>*Standard* headers. 

No, this is forbidden.
-- 
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
0
Reply markmcintyre (4547) 9/28/2005 8:55:29 PM

bhalicki@dodo.com.au wrote on 28/09/05 :
> In the following code I am trying to change the contents of a string:
>
> int main()
> {
>   char *string="testing";

This is not portable. The standard says that string literals are not 
guaranteed to be mutable.

   char const *string="testing";

is better and error prone.


>   rename(string);
>
>   return 0;
> }
>
> void rename(char *s)

'constness propagation' :

void rename(char const *s)

> {
>   printf("Character 1: %c\n",*s);
>   *s='a';

compile error due to const. You are now warned that there is something 
wrong in your design. Sure, because you are trying to modify a 
read-only object.

To fix that, you must use an initiaized array of char :

char string[] = "testing";

and keep the rest of your original code ...

>   printf("Character 1 now: %c\n",*c);

.... well, almost... what is 'c' ? You meant 's', I guess...

> }
>
> Anyway, I am sure this is possible but for some reason I'm getting
> segmentation faults at line *s='a'; when I attempt to change the value
> in which *s is currently pointing to, being the first character in the
> string.

Sure. Attempting to write to a string literal invokes an undefined 
behaviour.

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

"Clearly your code does not meet the original spec."
"You are sentenced to 30 lashes with a wet noodle."
-- Jerry Coffin in a.l.c.c++


0
Reply emdel (952) 9/28/2005 9:15:14 PM

bhalicki@dodo.com.au wrote:
> Hi all,
>
> In the following code I am trying to change the contents of a string:
>
> int main()
> {
>   char *string="testing";

The above assignment loses the const qualifier. In case you
are using gcc, -Wwrite-strings will emit warnings. Use arrays if
you want to modify content.

>cat str.c
#include <stdio.h>
int main (void)
{
   char *string = "testing";
   printf("%s\n", string);
   return 0;
}
>which gcc
gcc:     aliased to gcc -Wall -W -ansi -pedantic
>gcc str.c
>./a.out
testing
>gcc -Wwrite-strings str.c
str.c: In function `main':
str.c:4: warning: initialization discards qualifiers from pointer
target type
>


Karthik



>   rename(string);
> 
>   return 0;
> }
>

0
Reply kar1107 (89) 9/28/2005 9:27:55 PM

hemalatha.gopalakrishnan@gmail.com wrote:
> in the above program what is "c", not declared in the program, first u
> declare that and assign a value and then print it ok.  i think that
> there is no problem in the line *s='a';
> so try it and send me the result.

Sorry, my apologies, *c should have read *s.  I still can't figure this
one.  As far as I understand, *s is a pointer, which should point to a
memory location which currently holds the value 't' (first character in
string 'testing').  Without moving the pointer, I try to reassign this
to the value 'a', but it seg. faults.  I have even tried allocating
memory with malloc/memset, but still the same result.

I didn't want to use an array as I wanted to dynamically allocate
memory based on string size (at runtime).  I'm sure this has been done
before without arrays and it seems logical.

0
Reply bhalicki (29) 9/28/2005 10:29:26 PM

Mark McIntyre <markmcintyre@spamcop.net> writes:
> On 28 Sep 2005 02:13:26 -0700, in comp.lang.c , "David G. Hong"
> <kioria@gmail.com> wrote:
[...]
>>Although dubbed as *Standard* Input Ouput - not really a
>>standard. 
>
> Actually, they are - in order for a C compiler to be
> Standard-compliant, it must provide these functions.

Assuming (as we usually do around here) a hosted implementation rather
than a freestanding (embedded) implementation.

And as long as I'm nitpicking, it's the implementation, not
necessarily the compiler, that provides the standard functions.

But of course your point is correct.  Since the rename() function is
provided by <stdio.h>, "rename" is reserved for use as an identifier
with external linkage.  You could provide a static function called
"rename", but it would only cause confusion.

-- 
Keith Thompson (The_Other_Keith) kst-u@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.
0
Reply kst-u (21545) 9/28/2005 10:30:32 PM

bhalicki@dodo.com.au writes:
> hemalatha.gopalakrishnan@gmail.com wrote:
>> in the above program what is "c", not declared in the program, first u
>> declare that and assign a value and then print it ok.  i think that
>> there is no problem in the line *s='a';
>> so try it and send me the result.
>
> Sorry, my apologies, *c should have read *s.  I still can't figure this
> one.  As far as I understand, *s is a pointer, which should point to a
> memory location which currently holds the value 't' (first character in
> string 'testing').  Without moving the pointer, I try to reassign this
> to the value 'a', but it seg. faults.  I have even tried allocating
> memory with malloc/memset, but still the same result.
>
> I didn't want to use an array as I wanted to dynamically allocate
> memory based on string size (at runtime).  I'm sure this has been done
> before without arrays and it seems logical.

I don't understand.  Just yesterday, you wrote:

] Thanks for that information Walter.  I managed to get it working, by
] allocating the memory then using strcpy to load the string.

Your original code had several problems.  It declared a function
called "rename", which conflicts with the standard function of that
name.  It attempted to modify a string literal (a segmentation fault
is a likely symptom in that case).  And it used the name "c" rather
than "s", implying that the code you posted wasn't the actual code you
had tried.

If you're still having problems after fixing all these issues, try
posting your code again.  Copy-and-paste the *exact* code that you fed
to the compiler; if you re-enter it manually, we won't be able to
guess which errors are in the original code and which are new typos.

-- 
Keith Thompson (The_Other_Keith) kst-u@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.
0
Reply kst-u (21545) 9/28/2005 10:49:56 PM

kar1107@gmail.com wrote:
> bhalicki@dodo.com.au wrote:
> 
>>Hi all,
>>
>>In the following code I am trying to change the contents of a string:
>>
>>int main()
>>{
>>  char *string="testing";
> 
> 
> The above assignment loses the const qualifier.

No it doesn't. One of the quirks of the C language is that it is *not* 
const qualified. Modifying string literals is undefined behaviour 
(forbidden) because the standard explicitly states that it is and for no 
other reason.

 > In case you
> are using gcc, -Wwrite-strings will emit warnings. Use arrays if
> you want to modify content.

This is correct.

>>cat str.c
> 
> #include <stdio.h>
> int main (void)
> {
>    char *string = "testing";
>    printf("%s\n", string);
>    return 0;
> }

There is nothing wrong with the above code. The standard does not 
require a diagnostic and it does not invoke undefined behaviour.

>>which gcc
> 
> gcc:     aliased to gcc -Wall -W -ansi -pedantic
> 
>>gcc str.c
>>./a.out
> 
> testing
> 
>>gcc -Wwrite-strings str.c
> 
> str.c: In function `main':
> str.c:4: warning: initialization discards qualifiers from pointer
> target type

I agree that the warning is useful. Just not required by the standard 
and not provided by all compilers.
-- 
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
0
Reply spam331 (4024) 9/28/2005 11:24:07 PM

20 Replies
38 Views

(page loaded in 0.212 seconds)

Similiar Articles:


















7/13/2012 1:03:42 AM


Reply: