473,888 Members | 1,525 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can't dereference pointer to stack?

Why does the following give a segmentation fault?

void breakme(char* st) {
char* cp = st;
*cp = 'x' // This is the problem line.
}

int main() {
char* mine = "teststringfort estingpurposes" ;
breakme(mine);
}

Feb 10 '06 #1
9 2037
* Tu*********@gma il.com:
Why does the following give a segmentation fault?

void breakme(char* st) {
char* cp = st;
*cp = 'x' // This is the problem line.
}

int main() {
char* mine = "teststringfort estingpurposes" ;
breakme(mine);
}


Why not?

The program has undefined behavior.

Therefore, anything can happen, including a SIGSEGV.

If instead you ask, why does C++ allow that particular nastie?

That's to maintain backwards compatibility with C.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Feb 10 '06 #2

Tu*********@gma il.com wrote:
Why does the following give a segmentation fault?

void breakme(char* st) {
char* cp = st;
*cp = 'x' // This is the problem line.
}

int main() {
char* mine = "teststringfort estingpurposes" ;


This string is constant and cannot be changed. Change to "char mine[]
= " and it will work. This is because you will be declairing an array
of char instead of a pointer to an unmutable string.

Feb 10 '06 #3
Tu*********@gma il.com wrote:
Why does the following give a segmentation fault?

void breakme(char* st) {
char* cp = st;
*cp = 'x' // This is the problem line.
}

int main() {
char* mine = "teststringfort estingpurposes" ;
breakme(mine);
}

Modifying a static string literal is - whilst legal - undefined. The
statement
char* mine = "teststringfort estingpurposes" ;
is actually converting a const char * to char * (again which is legal
but deprecated). Result - undefined. In your case (probably most
compilers will do the same) - dummy spit.

--dakka
Feb 10 '06 #4
Thanks everyone.

This was from a string manipulation function I wrote that was seemingly
not working. The worst part is that it would have worked if I hadn't
used a string literal to test it.

Feb 10 '06 #5
hmm..
now I'm getting worried. Has something happened with c++, that
I am not aware of?
you can even do:(if you like to i dont see why though)
void breakme(char* st) {
char* cp = st;
*cp = 'x'; }
int main() {
breakme("testst ringfortestingp urposes");
}
This is a basic pointer..
I am a bit confused now.
And just so you know, I tested this (borland compiler set to ansi
complience and force c++ compile).
Please help me understand.
/Jesper

Feb 10 '06 #6
je****@alphacas h.se wrote:
hmm..
now I'm getting worried. Has something happened with c++, that
I am not aware of?
you can even do:(if you like to i dont see why though)
void breakme(char* st) {
char* cp = st;
*cp = 'x'; }
int main() {
breakme("testst ringfortestingp urposes");
}
This is a basic pointer..
I am a bit confused now.
And just so you know, I tested this (borland compiler set to ansi
complience and force c++ compile).
Please help me understand.


Understand what? You don't mention what it is that confuses you.

The code fragments shown exhibit undefined behavior. It may seem like a
tautology, but there is no defined behavior for undefined behavior. The
code is broken and should not be used, but you can't expect anything in
particular from it.

Brian

Feb 10 '06 #7

Alf P. Steinbach wrote:
* Tu*********@gma il.com:
Why does the following give a segmentation fault?

void breakme(char* st) {
char* cp = st;
*cp = 'x' // This is the problem line.
}

int main() {
char* mine = "teststringfort estingpurposes" ;
breakme(mine);
}


Why not?

The program has undefined behavior.

Therefore, anything can happen, including a SIGSEGV.

If instead you ask, why does C++ allow that particular nastie?

That's to maintain backwards compatibility with C.


The idea that modification of literals is undefined in C++ for the sake
of compatibility with C is quite ridiculous.

Other languages have similar restrictions against what is essentially
self-modifying code.

Modification of literals is also undefined in Lisp for instance. Is
that for compatibility with C also?

(setf (car '(a b c)) 42) ;; Nasal demons!
(setf (char "abc" 1) #\z) ;; ditto

This type of liberty with respect to literals allows for ROM-able code:
both the program code and its literal data can be compiled into a
single program image, which can then be put into write-protected
memory. The program can reference that data using a direct pointer into
that memory.

A literal should be thought of as a component of the program itself,
and not some external data. Through a literal quoting mechanism, a
program gains access to a piece of itself which it can use as data in a
computation.

If such objects had to be modifiable, then only their initial values
could be stored in that read-only memory. Modifiable storage would have
to be allocated for them at program startup, and the initial values
copied there. This is a waste of time and storage for objects which are
treated as immutable.

And let's not forget that immutable objects can also be compressed
together to save space through substructure sharing. If one string
literal matches a suffix of another, or possible the entire string,
then it can be represented as a pointer to that suffix. If those
objects could be modified, there would be surprising behaviors.
Changing one literal would change some unrelated string that shares
storage with it.

Many C and C++ implementations for virtual memory systems provide a
nice, accurate diagnostic for this error. The compiler places string
literals into the same object file sections as code, so literals are
co-allocated with code. The dynamic loader maps the program's
executable image file into the process address space as read only, so
any self modification (code or literal data) results in an instant
violation. It's a nice setup.

Feb 10 '06 #8
* Kaz Kylheku:
Alf P. Steinbach wrote:
* Tu*********@gma il.com:
Why does the following give a segmentation fault?

void breakme(char* st) {
char* cp = st;
*cp = 'x' // This is the problem line.
}

int main() {
char* mine = "teststringfort estingpurposes" ;
breakme(mine);
}

Why not?

The program has undefined behavior.

Therefore, anything can happen, including a SIGSEGV.

If instead you ask, why does C++ allow that particular nastie?

That's to maintain backwards compatibility with C.


The idea that modification of literals is undefined in C++ for the sake
of compatibility with C is quite ridiculous.


Yes.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Feb 10 '06 #9

<je****@alphaca sh.se> skrev i meddelandet
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
hmm..
now I'm getting worried. Has something happened with c++, that
I am not aware of?
you can even do:(if you like to i dont see why though)
void breakme(char* st) {
char* cp = st;
*cp = 'x'; }
int main() {
breakme("testst ringfortestingp urposes");
}
This is a basic pointer..
Yes, but the type of the string literal is 'const char*'. It is
convertible to non-const char*, just to be compatible with old C code.

Actually modifying (*cp = 'x';) the const data is what is the
undefined behaviour.

On some other compilers, this would cause a segfault, as the string
literal could be stored in a read-only segment. As usual though, one
possible outcome of the undefined behaviour is the nasty 'seems to
work'.
I am a bit confused now.


We all are. .-)
Bo Persson
Feb 11 '06 #10

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

Similar topics

26
7122
by: Brett | last post by:
I have created a structure with five fields. I then create an array of this type of structure and place the structure into an array element. Say index one. I want to assign a value to field3 of the structure inside the array. When I try this, an error about late assignment appears. Is it possible to assign a value to a structure field that is in an array? I'm currently getting around the problem by creating a new structure, assign...
11
1500
by: Tamas Demjen | last post by:
I was shocked to learn that VC++ 2005 Beta 2 can't catch Access Violation exceptions in unmanaged code. To reproduce this, I created a minimal Win32 console application: #include "stdafx.h" int _tmain(int argc, _TCHAR* argv) { int* p = 0;
6
5432
by: TuxC0d3 | last post by:
Hi! I'm diving into the some more ++ specific aspects of c++ (and finally accepting that c++ is more than "a plus added to c" :), so that means using namespaces, templates, std::strings, lists, vectors, operator overloading and what not.. And i was wondering if there is a way to override the global dereference operator, so to be able to check the address that one tries to dereference. This gives the ability to throw an exception when...
26
3077
by: Bill Reid | last post by:
Bear with me, as I am not a "professional" programmer, but I was working on part of program that reads parts of four text files into a buffer which I re-allocate the size as I read each file. I read some of the items from the bottom up of the buffer, and some from the top down, moving the bottom items back to the new re-allocated bottom on every file read. Then when I've read all four files, I sort the top and bottom items separately...
26
4528
by: =?iso-8859-1?q?Tom=E1s_=D3_h=C9ilidhe?= | last post by:
Do you think we can reach any kind of consensus on whether the following code's behaviour is undefined by the Standard? int my_array; int const *const pend = *(&my_array + 1); Considering the syntax of the language, then we definitely do dereference an invalid pointer... but if we consider the mechanics of the language, then we know that nothing "happens" when we dereference a pointer
0
9800
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11181
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
10778
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...
0
10439
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9597
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
7990
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
7148
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
5819
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...
3
3252
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.