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("tokeniz ing \"%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 8 4040
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("tokeniz ing \"%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
when i run your code in rh9, i got Segmentation Fault,
but if your gdb prog, it runs ok, why?
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????? ??????????????? ?????????????
? ??????????????? ??????????????? ??????????????? ????????????
Franklin Li <pe*******@hotm ai.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("tokeniz ing \"%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(st rlen(buf)+1);
/* ... (check) */
strcpy(buf2, buf);
if ((token = strtok(buf2, "/")) != NULL) {
^^^^
--
Stan Tobias
mailx `echo si***@FamOuS.Be dBuG.pAlS.INVALID | sed s/[[:upper:]]//g`
"S.Tobias" <si***@FamOuS.B edBuG.pAlS.INVA LID> writes: Franklin Li <pe*******@hotm ai.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("tokeniz ing \"%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_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.
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
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.
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>> This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 !
|
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 of the
destructor. So I think I am somehow using delete incorrectly, but I'm
not sure exaclty what I'm doing wrong.
I'd apprecitate any clarification and suggestions for rewriting the
below properly.
|
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 a local object when you
pass an object by reference.
But why use a reference? Is there any inherent advantage of using a
reference over using a pointer? My workplace discourages the use of
pointers when it comes to parameter passing. They...
|
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 area of ram that's
not reserved by the program. Accessing memory through such pointer is
likely to result in core dump (memory access violation)"
|
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...
char *a = "some text";
char *b = "some other text";
Why will this work? Needn't I initialize the pointers first? (malloc
| |
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), sizeof(s)/sizeof(char) - 1, stdout );
|
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.
|
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
|
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;
|
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.
---
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
|
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...
| |
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...
|
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,...
|
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...
|
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...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |