ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
I am wondering what happens in the followings situation:
char * test = "hi";
test = "how are you";
Now, the way I understand it, the first line creates a block of memory that contains "h" "i" and "\0". When I have the pointer point to a new string of characters,
if
1) a new block of memory is allocated, what happens to the old block of memory?
if
2) the memory is overwritten, then doesn't this create the possibility that the code unintentionally overwrites memory that shouldn't be touched?
When I really think about it, char *test and char test[] really are interchangeable, right? So the second should apply, I believe.
Since those strings are set at compile time, they're stored in memory (i think in a const area, but not sure). When you say 'x = "hello world";', you're just shifting the x pointer to another string which I cant for the life of me remember the name of.
char x[] and char *x are fairly interchangable, yes
I forget exactly where static strings are stored in memory, but I think they're flagged as read-only. So you would pass your pointer to char to cin, which would try and write to this illegal memory. Off the top of my head I'm guessing segfault...
I am just a hobbyist programmer but there appear to be some basic flaws in your thinking in the above code fragment.
First, you can't assign a value of 'hi' to the pointer 'test' without first assigning it an address of something (the variable 'q' in my example).
Second, the compiler (at least gcc) will allow (but complain), a multicharacter constant in the example below but the output is not what you expect and you are courting crashes with anything more complicated.
#include "stdio.h"
main()
{
char *test, q;
test = &q; /* get q's address */
*test = 'hi'; /* assign q a value using a pointer */
printf("q's value is %c", q); /* simple printf statement to illustrate */
)
Save the above fragment as test.c, run 'gcc test.c' then execute the resulting a.out. Then edit the test.c file to take out the i in 'hi' and see what happens. Hint: Look at the warnings from the compiler as it builds the a.out. Also fiddle with the single quotes I replaced your double quotes with in the assignment statement and see what happens.
nz
EDIT put some whitespace in between the end of my statements and the first comment forward slash character if you cut and past the fragment. Still trying to get used to the darn LQ editor
1. Yes, the string constants are allocated at compile time, in a (typically read-only) area called the "TEXT" section.
2. Kroenecker's original post:
Code:
char * test = "hi";
test = "how are you";
was perfectly correct. He declared a pointer ("test"), he assigned it to something (the 3-byte constant "hi\0", and then assigned it to something else (the 12-byte constant "how are you\0". All well and good.
3. For whatever it's worth, the following might explain a bit better:
Code:
/*
* 1. gcc compile:
* gcc -g -o xyz xyz.c
*
* 2. Debug session:
* gdb command: gdb response:
* ----------- ------------
* (gdb) b main Breakpoint 1 at 0x80483a8: file x.c, line 5.
* (gdb) r Starting program: /tmp/x
* (gdb) n 6 test = "hi";
* (gdb) p test $2 = 0x0
* (gdb) n 8 test = "how are you";
* (gdb) p test $3 = 0x80484e8 "hi"
* (gdb) n 10 return 0;
* (gdb) p test $4 = 0x80484eb "how are you"
*/
#include <stdio.h>
main (int argc, char *argv[])
{
/* #/Bytes Where When */
/* Allocated Allocated Allocated */
/* --------- --------- --------- */
char * test = 0; /* 4 bytes STACK RUNTIME */
test = "hi"; /* 3 bytes TEXT SECTION COMPILE TIME */
test = "how are you"; /* 12 bytes TEXT SECTION COMPILE TIME */
return 0;
}
Very much appreciated. That is the first time that I have been able to use gdb. Thanks so much.
I have another question now about std::cin.getline(char*, int n);
If a user inputs a string that is longer than n, it seems that all other getline calls go without putting any value into the buffer be it a new buffer or the old one.
I used gdb to step through, but it wasn't apparent what was going wrong.
Well after googling about, I found out about a few helpful stream functions:
stream.fail() and stream.clear()
Basically if getline receives a stream that is too long for the buffer, the fail flag will be set. This flag can be tested by using fail(). So in my case since I'm using cin:
std::cin.getline(buffer, 10);
std:: out << buffer << std::endl;
if( std::cin.fail() )
{
std::cout << "Too much user input... " << std::endl;
std::cin.clear(); // This clears the flag
}
//Now the next getline call will resume where the previous one had
//cut off.
std::cin.getline(second_buffer, 10);
std::cout << second_buffer << std::endl;
In this way you could use cin.fail() in a do while statement to ensure that the user inputs a string that is small enough to fit into your buffer.
Thanks all. I'm sure I will be coming up with more questions in the coming weeks
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.