473,749 Members | 2,597 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

why segmentation fault when copying a character?

Hi,
This might be a sort of FAQ, but I don't see why,
so I would someone help me to understand what's wrong?

I've just created following code which wold trim
white space(s) in a (given) string.
But, it resulted the Segmentation fault, and so as
when running in gdb (saying "Program received signal
SIGSEGV, Segmentaion fault at *p++ = *st++").
The platform is Linux kernel 2.4.27, gcc version
2.95.4 20011002.

/*-------------------------------------*/
#include <stdio.h>
#include <ctype.h>

int main(int argc, char ** argv)
{
char *st = "Hey, how are you?";
char *p, *s;

p = s = st;

while( *st )
{
if ( isspace( (int)*st ) )
st++;
else
*p++ = *st++;
}
*p = '/0';

printf("whitesp ace trimed : %s\n", s);
}

Compile itself doesn't complain anything, and I don't
see what's wrong with copying the character in the
string to the other place (in memory) where should not
overlap the end of the string ('/0') of the original
string.
Colud someone help me to understand what's wrong with
this code?

Thanks and Best Regards,
Cocy
Nov 14 '05 #1
10 2391
Cocy <ku*********@ho tmail.com> spoke thus:
char *st = "Hey, how are you?";
char *p, *s;
p = s = st;


p, s, and st all point at the same string literal. You may not
attempt to modify a string literal; this is most likely the source of
your troubles.

<ot>You can pass an option to gcc to make the code work as is.</ot>

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cybers pace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #2
ku*********@hot mail.com (Cocy) wrote in
news:55******** *************** ***@posting.goo gle.com:
Hi,
This might be a sort of FAQ, but I don't see why,
so I would someone help me to understand what's wrong?

I've just created following code which wold trim
white space(s) in a (given) string.
But, it resulted the Segmentation fault, and so as
when running in gdb (saying "Program received signal
SIGSEGV, Segmentaion fault at *p++ = *st++").
The platform is Linux kernel 2.4.27, gcc version
2.95.4 20011002.

/*-------------------------------------*/
#include <stdio.h>
#include <ctype.h>

int main(int argc, char ** argv)
{
char *st = "Hey, how are you?";


If you defined this as it really is:

const char *st = "Hey, I cannot be modified!";

the reason should jump out at you (hint: note the 'const' keyword).

--
- Mark ->
--
Nov 14 '05 #3
Cocy wrote:
Hi,
This might be a sort of FAQ, but I don't see why,
so I would someone help me to understand what's wrong?

http://www.eskimo.com/~scs/C-faq/q1.32.html


Brian Rodenborn
Nov 14 '05 #4
Dear Christopher, Mark, and Brian.

Thank you very much for you guys comment, I really appreciate.
I got it, and I have a lot to learn.

Thank you again!
Cocy
Nov 14 '05 #5
Christopher Benson-Manica <at***@nospam.c yberspace.org> wrote:
Cocy <ku*********@ho tmail.com> spoke thus:

p, s, and st all point at the same string literal.

<ot>You can pass an option to gcc to make the code work as is.</ot>


But this is a very bad idea, because it doesn't get rid of the bug.

Richard
Nov 14 '05 #6
On 12 Oct 2004 18:55:34 GMT, "Mark A. Odell" <od*******@hotm ail.com>
wrote in comp.lang.c:
ku*********@hot mail.com (Cocy) wrote in
news:55******** *************** ***@posting.goo gle.com:
Hi,
This might be a sort of FAQ, but I don't see why,
so I would someone help me to understand what's wrong?

I've just created following code which wold trim
white space(s) in a (given) string.
But, it resulted the Segmentation fault, and so as
when running in gdb (saying "Program received signal
SIGSEGV, Segmentaion fault at *p++ = *st++").
The platform is Linux kernel 2.4.27, gcc version
2.95.4 20011002.

/*-------------------------------------*/
#include <stdio.h>
#include <ctype.h>

int main(int argc, char ** argv)
{
char *st = "Hey, how are you?";
If you defined this as it really is:

const char *st = "Hey, I cannot be modified!";


Bad example. In C, a pointer to string literal has the type 'pointer
to char', and specifically does not have the type 'pointer to const
char'. String literals may or may not be const. Attempting to modify
a string literal in C produces undefined behavior because the standard
specifically says so, not because the type of the string literal is
'array of const char'.

the reason should jump out at you (hint: note the 'const' keyword).


Nope, just plain wrong. There is absolutely no const keyword implied
in any way for string literals in C. You should not modify them
because the standard says you should not, not because they are const
qualified.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #7
Jack Klein wrote:
"Mark A. Odell" <od*******@hotm ail.com> wrote in comp.lang.c:
.... snip ...
the reason should jump out at you (hint: note the 'const' keyword).


Nope, just plain wrong. There is absolutely no const keyword
implied in any way for string literals in C. You should not modify
them because the standard says you should not, not because they are
const qualified.


However you are well advised to define those strings as const
anyhow, because then you will probably get an alert from the
compiler if you misuse them. gcc has a -Wconstant-strings
available to do it automatically.

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 14 '05 #8
Dear folks,

Thank you for you guys comment.

Ok, I understood that I can't safely modify the
strings after I've initialized it because it's
"const".
The page
http://www.eskimo.com/~scs/C-faq/q1.32.html
says like "the string may be stored in read-only
memory", and I suppose this explains the string
may be stored in "the memory area which is
assigned to be read-only", by the expression
"read-only memory".

If it is correct (I don't care whether it's correct
or not), where is the area?, who decide the area?
I mean does the compiler tell to someone (OS?) like
"please let this program use this meory area as to
be const"? or does OS decide like "Oh, you, the
program, I'll keep the string into the safety area
so that you can't modify later"?
In other word, does the compiler knows where the
"read-only memory", or only OS knows where it is?
(is only OS able to decide where it is)?

And where is the area actually? Is is this area so
called "heap"?
I guess I have to learn a lot to fully understand
my question. Is there any source to learn about
these things? (please don't say "take the class in
school" :-) Does the assembly code tell me those
stuffs?

Thanks and Best Regards,
Cocy
Nov 14 '05 #9
In article <55************ **************@ posting.google. com>,
ku*********@hot mail.com (Cocy) wrote:
Dear folks,

Thank you for you guys comment.

Ok, I understood that I can't safely modify the
strings after I've initialized it because it's
"const".
The page
http://www.eskimo.com/~scs/C-faq/q1.32.html
says like "the string may be stored in read-only
memory", and I suppose this explains the string
may be stored in "the memory area which is
assigned to be read-only", by the expression
"read-only memory".

If it is correct (I don't care whether it's correct
or not), where is the area?, who decide the area?
I mean does the compiler tell to someone (OS?) like
"please let this program use this meory area as to
be const"? or does OS decide like "Oh, you, the
program, I'll keep the string into the safety area
so that you can't modify later"?
In other word, does the compiler knows where the
"read-only memory", or only OS knows where it is?
(is only OS able to decide where it is)?
Generally, the compiler and linker have almost complete control over
this, and merely leave instructions for the OS and dynamic linker to
follow.
And where is the area actually? Is is this area so
called "heap"?
On UNIX, it's typically the "read-only data segment", or ".rodata".
During linking, this will usually be merged (along with ".init",
".fini", and any number of other read-only segments) with "text"
segment into a "program header" covering all of the read-only loadable
segments. You can view this by using (on linux):

% objdump -x /path/to/binary

or, (on Solaris):

% elfdump /path/to/binary

Look for "Program Header" and "Section", and start lining things up.
I guess I have to learn a lot to fully understand
my question. Is there any source to learn about
these things? (please don't say "take the class in
school" :-) Does the assembly code tell me those
stuffs?


It's more the linker -- _Linkers and Loaders_ by John R. Levine (ISBN
1558604960) is the best book I've run across for these sorts of details.
You could also google for documentation on ELF (Executable Linking
Format), which is the UNIX standard format.

Cheers,
- jonathan
Nov 14 '05 #10

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

Similar topics

2
6807
by: sivignon | last post by:
Hi, I'm writing a php script which deals with 3 ORACLE databases. This script is launch by a script shell on an linux machine like this : /../php/bin/php ./MySript.php (PHP 4.3.3) My script works fine and do all what I need. But at the end of the execution, I can read "Segmentation Fault". The segmentation fault appear at the end of my script execution,
6
2589
by: AMT2K5 | last post by:
Hello guys. I have a function, cleanSpace . I was told from another source that the problem is, is that the function is acting on constant string literal. To fix this I was told to take the incoming string, copy it to a buffer, work on the buffer and copy the buffer back to the original. I tried but no sucess. The seg fault is shown after the code snippet below.
9
31925
by: Maksim Kasimov | last post by:
Hello, my programm sometime gives "Segmentation fault" message (no matter how long the programm had run (1 day or 2 weeks). And there is nothing in log-files that can points the problem. My question is how it possible to find out where is the problem in the code? Thanks for any help. Python 2.2.3 FreeBSD -- Best regards,
5
1787
by: Verrigan | last post by:
I'm trying to pass an array to a function, and change the values of that array, but I can't seem to figure it out.. Please help me figure out what I'm doing wrong... Any help would be appreciated... Even if it's "You can't change the value of a passed array." :) Thanks! Code: static int get_command_args(char *msg, char **args) { char *p; int i, loops;
10
401
by: F?bio Botelho | last post by:
Sorry About the english.... This program copy one file to another , but when i run it it's gives-me an error: Segmentation fault I don't understand ... because it pass my test : opens the first file and create the second. If any one could give me a help I would be apreciated. thanks.
3
11440
by: Zheng Da | last post by:
Program received signal SIGSEGV, Segmentation fault. 0x40093343 in _int_malloc () from /lib/tls/libc.so.6 (gdb) bt #0 0x40093343 in _int_malloc () from /lib/tls/libc.so.6 #1 0x40094c54 in malloc () from /lib/tls/libc.so.6 It's really strange; I just call malloc() like "tmp=malloc(size);" the system gives me Segmentation fault I want to write a code to do like a dynamic array, and the code is as
0
1923
by: jgarber | last post by:
Hello, I just upgraded MySQLdb to the 1.2.0 version provided by Redhat Enterprise Linux ES4. At that point I began to get segfaults when importing twisted after MySQLdb, but not before. -- RedHat Enterprise Linux ES 4 (fully updated) Python 2.3.4 mysql-python (MySQLdb) version 1.2.0
3
5187
by: madunix | last post by:
My Server is suffering bad lag (High Utlization) I am running on that server Oracle10g with apache_1.3.35/ php-4.4.2 Web visitors retrieve data from the web by php calls through oci cobnnection from 10g release2 PHP is configured with the following parameters './configure' '--prefix=/opt/oracle/php' '--with-apxs=/opt/oracle/apache/bin/apxs' '--with-config-file-path=/opt/oracle/apache/conf' '--enable-safe-mode' '--enable-session'...
3
3919
by: jr.freester | last post by:
I have created to classes Matrix and System. System is made up of type matrix. ---------------------------------------------------------------------------------- class Matrix { private: int row, col; double *data public: Matrix(const int& M, const int& N): row(M), col(N)
0
9568
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
9389
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
9335
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
8257
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6801
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6079
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
4709
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...
0
4881
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2794
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.