473,813 Members | 3,539 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to identify a pointer to a string literal

Hello,

If we have c code like what's below, we will get an error because in
the stringManipulat or function we attempt to modify a string literal on
the second call to the function. My question is: in the
stringManipulat or function, is there any way to identify if the char*
is pointing to writable memory space to to a string literal?

Sure, the example is trivial, but we run into such problems when the
function call stack gets 20 functions deep! Thanks in advance!

int stringManipulat or(char *str)
{
/* check here to see if string is writable? */
str[0] = 'A';
str[1] = 'B';
}

int main()
{
char string_array[10] = "thisisok";

stringManipulat or(string_array );
stringManipulat or("thisisbad") ; /* shouldn't do this */
}

Jan 7 '06 #1
12 2650

<we***********@ gmail.com> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
Hello,

If we have c code like what's below, we will get an error because in
the stringManipulat or function we attempt to modify a string literal on
the second call to the function. My question is: in the
stringManipulat or function, is there any way to identify if the char*
is pointing to writable memory space to
I assume you mean 'rather than'
to a string literal?
No there is not.

If you want to ensure that the function will not
modify what the pointer points to, declare it as 'const':

int stringManipulat or(const char *str)
Sure, the example is trivial, but we run into such problems when the
function call stack gets 20 functions deep!
The function call nesting level has nothing to do with
this.

int stringManipulat or(char *str)
{
/* check here to see if string is writable? */
str[0] = 'A';
str[1] = 'B';
}

int main()
{
char string_array[10] = "thisisok";

stringManipulat or(string_array );
stringManipulat or("thisisbad") ; /* shouldn't do this */
}


If the function must modify what the pointer points to,
then you can't declare it as const, and must resort to
(gasp) self-discipline in order to refrain from passing
a pointer to a non-modifiable object. There's also another
thing you should take care with: make sure that you only
pass a pointer to a string of at least a length of two
characters (plus one more for the terminator). E.g.
this will produce undefined behavior:

char a[] = "";
stringManipulat or(a);
Finally, note that the language reserves to the implementation
any external names beginning with 'str' followed by a lower case
character. Your name 'stringManipula tor' violates this rule.

-Mike
Jan 7 '06 #2
we***********@g mail.com a écrit :
If we have c code like what's below, we will get an error because in
the stringManipulat or function we attempt to modify a string literal on
the second call to the function.


Define the string literal with the 'const' qualifier. It will ring a
bell when you pass it eo the function.

int stringManipulat or(char *str)
{
/* check here to see if string is writable? */
str[0] = 'A';
str[1] = 'B';
}

int main()
{
char string_array[10] = "thisisok";

stringManipulat or(string_array );
stringManipulat or((char const *)"thisisbad" ); /* shouldn't do this
(Awsome) */

/* or */

char const * p = "thisisbad" ;
stringManipulat or(p);

return 0;
}

You also can activate a compiler/lint checking (like gcc's
-Wwrite-strings), at last at debug time.

--
A+

Emmanuel Delahaye
Jan 7 '06 #3
we***********@g mail.com said:
Hello,

If we have c code like what's below, we will get an error because in
the stringManipulat or function we attempt to modify a string literal on
the second call to the function. My question is: in the
stringManipulat or function, is there any way to identify if the char*
is pointing to writable memory space to to a string literal?
If the function doesn't write to the string you accept as a parameter, make
it const char *. Don't pass string literals as arguments except where const
char * is expected.
stringManipulat or("thisisbad") ; /* shouldn't do this */


So don't. The time to get this right is when you're writing the calling
code.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jan 7 '06 #4
On Fri, 6 Jan 2006 15:03:11 UTC, we***********@g mail.com wrote:
Hello,

If we have c code like what's below, we will get an error because in
the stringManipulat or function we attempt to modify a string literal on
the second call to the function. My question is: in the
stringManipulat or function, is there any way to identify if the char*
is pointing to writable memory space to to a string literal?

Sure, the example is trivial, but we run into such problems when the
function call stack gets 20 functions deep! Thanks in advance!

int stringManipulat or(char *str)
{
/* check here to see if string is writable? */
str[0] = 'A';
str[1] = 'B';
}

int main()
{
char string_array[10] = "thisisok";

stringManipulat or(string_array );
is defined
stringManipulat or("thisisbad") ; /* shouldn't do this */
undefined behavior.
}

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!
Jan 8 '06 #5
Herbert Rosenau wrote:
On Fri, 6 Jan 2006 15:03:11 UTC, we***********@g mail.com wrote:
Hello,

If we have c code like what's below, we will get an error because in
the stringManipulat or function we attempt to modify a string literal on
the second call to the function. My question is: in the
stringManipulat or function, is there any way to identify if the char*
is pointing to writable memory space to to a string literal?

Sure, the example is trivial, but we run into such problems when the
function call stack gets 20 functions deep! Thanks in advance!

int stringManipulat or(char *str)
{
/* check here to see if string is writable? */
str[0] = 'A';
str[1] = 'B';
}

int main()
{
char string_array[10] = "thisisok";

stringManipulat or(string_array );


is defined
stringManipulat or("thisisbad") ; /* shouldn't do this */


undefined behavior.


If you are going to take the time to post a response, please at least
read the post you are responding to first. The OP obviously knows that
the latter is undefined, he was asking if there is any way for the
program to know at runtime that it was passed a pointer to a string
literal.

Robert Gamble

Jan 9 '06 #6
Ok, so if a compiler or lint can determine that the string is not
modifiable, then why can't I?

Jan 9 '06 #7

<we***********@ gmail.com> wrote in message
news:11******** *************@g 44g2000cwa.goog legroups.com...
Ok, so if a compiler or lint can determine that the string is not
modifiable, then why can't I?


You can - if you've a brain like a C parser, and use it to parse to an
arbitrary depth.
Jan 9 '06 #8

<we***********@ gmail.com> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
Hello,

If we have c code like what's below, we will get an error because in
the stringManipulat or function we attempt to modify a string literal on
the second call to the function. My question is: in the
stringManipulat or function, is there any way to identify if the char*
is pointing to writable memory space to to a string literal?

Sure, the example is trivial, but we run into such problems when the
function call stack gets 20 functions deep! Thanks in advance!

int stringManipulat or(char *str)
{
/* check here to see if string is writable? */
str[0] = 'A';
str[1] = 'B';
}

int main()
{
char string_array[10] = "thisisok";

stringManipulat or(string_array );
stringManipulat or("thisisbad") ; /* shouldn't do this */
}


Maybe I'm reading more 'in-between the lines' that I ought to here, but, I
suspect you may have a codebase that you're porting to a platform [or that
uses a different compiler for the same platform] that allows this undefined
behaviour? And, that you'd like to run the code on your main development
platform *and* find such things? If the answer's yes, besides using lint
etc, there is a hack that you might use to get some big hints as to where
your code's got this particular problem, I won't go into it here [unless
what I say hits the nail on the head] - as it's damn awful!


Jan 9 '06 #9
In article <11************ *********@g44g2 000cwa.googlegr oups.com>,
we***********@g mail.com <we***********@ gmail.com> wrote:
Ok, so if a compiler or lint can determine that the string is not
modifiable, then why can't I?


Short answer: *You* can, but your program can't.
Slightly longer answer: Because they have access to the source code; your
program (at runtime) does not.

Longer answer: Subject to the usual caveat of:

Not portable. Can't discuss it here. Blah, blah, blah.

You could probably figure it out yourself with a little experimentation ;
figure out what sort of addresses string literals have vs. what sort of
addresses allocated space has (with all the standard caveats of: on your
platform, your compiler, etc, etc) and then write the functions to check
the value of the pointer and behave accordingly.

Jan 9 '06 #10

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

Similar topics

10
2069
by: Chris Mantoulidis | last post by:
I see some really weird output from this program (compiled with GCC 3.3.2 under Linux). #include <iostream> using namespace std; int main() { char *s; s = "test1"; cout << "s = " << s << " and &s = " << &s << "\n";
22
3298
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 !
110
9972
by: Mr A | last post by:
Hi! I've been thinking about passing parameteras using references instead of pointers in order to emphasize that the parameter must be an object. Exemple: void func(Objec& object); //object must be an object instead of
4
1295
by: Paul | last post by:
hi, there, In the following codes, If I change the varible "string "in main() to char* string=" this is the test string "; the program will be crashed. can someone tell me why and how to modify the code so that I can still use char * string? thanks. ================================ #include <stdio.h>
9
2036
by: TuAmigoFiel | last post by:
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 = "teststringfortestingpurposes"; breakme(mine);
25
2163
by: dis_is_eagle | last post by:
Hi.I have a question on the following statement. char* a="hello"; The question is where "hello" gets stored.Is it in some static area ,stack or heap.I have observed that attempting to modify "hello" results in segmentation fault.Thanks for any help. Eric
41
2388
by: Dead Loop | last post by:
Hi all, I'm a beginner and my question is: Are there any differences between char *p = "Hello, world!"; and const char *p = "Hello, world!"; ?
19
2475
by: mail1779205 | last post by:
I (certainly) hope I know what this function does: char *fun(void){ char *ptr = "Hello World"; return ptr; } It returns a pointer to a string stored somewhere in the memory and is read-only. Does the following function do the same thing and is the
156
5919
by: Lame Duck | last post by:
Hi Group! I have a vector<floatvariable that I need to pass to a function, but the function takes a float * arguement. That's OK, I can convert by doing &MyVector.front(), but when I get back a float * from the function, how to convert that back to a vector? Thanks in advance!
0
9607
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
10667
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
9222
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
7681
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
6897
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
5568
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
5705
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3885
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3030
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.