473,387 Members | 1,420 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

question for char point.

Hi all,

I have one simple program:
#define __EXTENSIONS__
#include <stdio.h>
#include <string.h>

int main() {
char *buf="5/90/45";
char *token;
char *lasts;

printf("tokenizing \"%s\" with strtok():\n", buf);
if ((token = strtok(buf, "/")) != NULL) {
printf("token = "%s\"\n", token);
while ((token = strtok(NULL, "/")) != NULL) {
printf("token = \"%s\"\n", token);
}
}
}

When I compile it using CC and got one Warning: String literal converted to
char* in assignment.
When I run it and got Segmentation Fault(coredump).

Then I changed defination as below:
char str[] = "5/90/45";
char *buf = str;

Then this is no warning and I can get the correct result.

Could you give me the reason?

I think I can use char *point = "string" directly.

Thansk.

Franklin
Nov 14 '05 #1
8 4000

in msdn i got

char *strtok( char *strToken, const char *strDelimit );
wchar_t *wcstok( wchar_t *strToken, const wchar_t *strDelimit );
Parameters

strToken
String containing token(s)
strDelimit
Set of delimiter characters
Libraries

All versions of the C run-time libraries.

All of these functions return a pointer to the next token found in
strToken. They return NULL when no more tokens are found. Each call
modifies strToken

~~~~~~~~~~~~~~~~~~~

~~~~~~~~~~~~~~~~~~

by substituting a NULL character for each delimiter that is
encountered.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~

now you see strtok will modify the content of the first argument.

but your code write

char * buf = "";

which you can not modify its content.

use char buf[] = "" is ok,
because buf 's cotent become modifiable.

baumann@pan

Franklin Li wrote:
Hi all,

I have one simple program:
#define __EXTENSIONS__
#include <stdio.h>
#include <string.h>

int main() {
char *buf="5/90/45";
char *token;
char *lasts;

printf("tokenizing \"%s\" with strtok():\n", buf);
if ((token = strtok(buf, "/")) != NULL) {
printf("token = "%s\"\n", token);
while ((token = strtok(NULL, "/")) != NULL) {
printf("token = \"%s\"\n", token);
}
}
}

When I compile it using CC and got one Warning: String literal converted to
char* in assignment.
When I run it and got Segmentation Fault(coredump).

Then I changed defination as below:
char str[] = "5/90/45";
char *buf = str;

Then this is no warning and I can get the correct result.

Could you give me the reason?

I think I can use char *point = "string" directly.

Thansk.

Franklin


Nov 14 '05 #2
when i run your code in rh9, i got Segmentation Fault,
but if your gdb prog, it runs ok, why?

Nov 14 '05 #3
when i run your code in rh9, i got Segmentation Fault,
but if run your code in debug mode ,
gdb prog,
and step by step it runs ok,

?????????????????????????????????????????????????? ????????
??????????????????????why????????????????????????? ????????
? ?????????????????????????????????????????????????? ???????

Nov 14 '05 #4
Franklin Li <pe*******@hotmai.com> wrote:
Hi all, I have one simple program:
#define __EXTENSIONS__
#include <stdio.h>
#include <string.h> int main() {
char *buf="5/90/45"; Here `buf' points to a static string, which is in read-only
memory. It's okay, until... char *token;
char *lasts; printf("tokenizing \"%s\" with strtok():\n", buf);
if ((token = strtok(buf, "/")) != NULL) { ....here: strtok tries to modify the string, which you are not
allowed to do.
You have to make a copy of the string, that can be modified, which.... printf("token = "%s\"\n", token);
while ((token = strtok(NULL, "/")) != NULL) {
printf("token = \"%s\"\n", token);
}
}
} When I compile it using CC and got one Warning: String literal converted to
char* in assignment.
When I run it and got Segmentation Fault(coredump). Then I changed defination as below:
char str[] = "5/90/45"; .... you're sort of doing here. `str' is an automatic array ("on stack"),
which you initialize with the string literal (this initialization might
for example copy the string from read-only memory to the new array). char *buf = str; Then this is no warning and I can get the correct result. Could you give me the reason? I think I can use char *point = "string" directly.


You can use the pointer `point' anyway you want, but not what
it points to.
Another way to change the program would be to malloc() and copy,
and pass the copy to strtok():
char *buf="5/90/45";
char *buf2=malloc(strlen(buf)+1);
/* ... (check) */
strcpy(buf2, buf);
if ((token = strtok(buf2, "/")) != NULL) {
^^^^

--
Stan Tobias
mailx `echo si***@FamOuS.BedBuG.pAlS.INVALID | sed s/[[:upper:]]//g`
Nov 14 '05 #5
"S.Tobias" <si***@FamOuS.BedBuG.pAlS.INVALID> writes:
Franklin Li <pe*******@hotmai.com> wrote:

[...]
char *buf="5/90/45";

Here `buf' points to a static string, which is in read-only
memory. It's okay, until...
char *token;
char *lasts;

printf("tokenizing \"%s\" with strtok():\n", buf);
if ((token = strtok(buf, "/")) != NULL) {

...here: strtok tries to modify the string, which you are not
allowed to do.


Actually, it's worse than that. The string literal may or may not be
in read-only memory. Attempting it to modify it invokes undefined
behavior.

--
Keith Thompson (The_Other_Keith) 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.
Nov 14 '05 #6
Franklin Li wrote:
char *buf="5/90/45";
You are allocating a pointer to a string literal (which may
or may not reside in read-only memory; nevertheless, it's
considered read-only).
if ((token = strtok(buf, "/")) != NULL) {
strtok modifies the contents pointed to by buf, but the contents
are read-only, so modification is not permitted.
Then I changed defination as below:
char str[] = "5/90/45";
Here, you are allocating an array of chars containing the string "5/90/45".
char *buf = str;


And here, you are allocating a pointer that points to that array,
so the contents of the array (str) pointed to by the pointer (buf)
are writable, thus no errors.

You could use 'if ((token = strtok(str, "/")) != NULL)' as well or,
as I'd prefer, 'if (!(token = strtok(str, "/")))'.

-atl-
--
A multiverse is figments of its own creations
Nov 14 '05 #7


Franklin Li wrote:
Hi all,

I have one simple program:
#define __EXTENSIONS__
#include <stdio.h>
#include <string.h>

int main() {
char *buf="5/90/45";
This declares buf to be a pointer to a string constant. String
constants may or may not be writable, depending on the particular
implementation; in your case, they're not. In general, it's best to
assume they're not.

strtok() has to be able to modify the buffer it's searching (it needs
to be able to replace the delimiters with a 0). Hence your warning and
your core dump (trying to write to non-writable memory).

[snip]
Then I changed defination as below:
char str[] = "5/90/45";
char *buf = str;
str is a statically allocated array of char, implicitly sized based on
the initializer, and the contents of the initializer are copied to it.
The contents of str are writable.

Then this is no warning and I can get the correct result.

Could you give me the reason?

I think I can use char *point = "string" directly.


You can when you aren't trying to modify the string.

Nov 14 '05 #8
On 4 Jun 2005 14:57:30 -0700, jo*******@my-deja.com wrote:


Franklin Li wrote:
Hi all,

I have one simple program:
#define __EXTENSIONS__
#include <stdio.h>
#include <string.h>

int main() {
char *buf="5/90/45";


This declares buf to be a pointer to a string constant. String
constants may or may not be writable, depending on the particular
implementation; in your case, they're not. In general, it's best to
assume they're not.


Whether they are physically writable or not may be an implementation
detail but any attempt to modify a string literal invokes undefined
behavior.

<<Remove the del for email>>
Nov 14 '05 #9

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

Similar topics

22
by: lokman | last post by:
Hi, In the following code, can someone tell me the difference between *p++ and p++ ? I can see both achieve the same result. Thanks a lot !
16
by: cppaddict | last post by:
Hi, I am deleting some objects created by new in my class destructor, and it is causing my application to error at runtime. The code below compiles ok, and also runs fine if I remove the body...
26
by: Desmond Liu | last post by:
I've read articles like Scott Meyer's EC++ (Item 22) that advocate the use of references when passing parameters. I understand the reasoning behind using references--you avoid the cost of creating...
20
by: __PPS__ | last post by:
Hello everybody in a quiz I had a question about dangling pointer: "What a dangling pointer is and the danger of using it" My answer was: "dangling pointer is a pointer that points to some...
3
by: Chris Mantoulidis | last post by:
I never liked pointers really much, so I decided to stay away from them for a while. I know they're useful, so now I decided to actually learn how the work, use them, etc. Here's my question......
30
by: Christopher Benson-Manica | last post by:
Given the following: char s="Hello, world\n!"; Are all the following guaranteed to produce the same output? printf( "%s", s ); fprintf( stdout, "%s", s ); fwrite( s, sizeof(char),...
2
by: akshayrao | last post by:
could someone point me in the right direction regarding this question?? http://groups.google.com/group/programpara/browse_thread/thread/75b58c897f890930 thanks.
23
by: Kenneth Brody | last post by:
Given the following: char *ptr1, *ptr2; size_t n; ptr2 = ptr1 + n; Assuming ptr1 is a valid pointer, is the following guaranteed to be true? (ptr2 - ptr1) == n
15
by: sethukr | last post by:
Hi everybody, While running the following program in GCC, i'm very much screwed. main() { char *ptr1; char arr; int i; char *ptr2;
25
by: Why Tea | last post by:
Thanks to those who have answered my original question. I thought I understood the answer and set out to write some code to prove my understanding. The code was written without any error checking....
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...

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.