473,396 Members | 1,797 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Basic question about pointers

I have a very elementary question about pointers. Please pardon me
for my ignorance of C

int main()
{
int* i;
*i = 1 //at times this may give me a core dump.
const char* str = "test"; //This seems to be a valid construct.
}

Now I understand that when we declare int* i, we just have a pointer
that may point to any place. If we try to store something in it, we
may get a segmentation fault. But why does const char* str = "test"
work? Do we not need to allocate memory for str first? Can someone
please shed some light on this?

Thanks in advance

Jul 16 '07 #1
13 1451
On Jul 15, 10:14 pm, Aarti <aarti.sa...@gmail.comwrote:
I have a very elementary question about pointers. Please pardon me
for my ignorance of C

int main()
{
int* i;
*i = 1 //at times this may give me a core dump.
const char* str = "test"; //This seems to be a valid construct.
}

Now I understand that when we declare int* i, we just have a pointer
that may point to any place. If we try to store something in it, we
may get a segmentation fault. But why does const char* str = "test"
work? Do we not need to allocate memory for str first? Can someone
please shed some light on this?

Thanks in advance
http://c-faq.com/decl/strlitinit.html

Jul 16 '07 #2
On Sun, 15 Jul 2007 20:14:33 -0700, Aarti <aa*********@gmail.com>
wrote:
>I have a very elementary question about pointers. Please pardon me
for my ignorance of C

int main()
{
int* i;
*i = 1 //at times this may give me a core dump.
const char* str = "test"; //This seems to be a valid construct.
}

Now I understand that when we declare int* i, we just have a pointer
that may point to any place. If we try to store something in it, we
may get a segmentation fault. But why does const char* str = "test"
Whether you get a segmentation fault or not, the effort to evaluate
any variable with an indeterminate value invokes undefined behavior.
>work? Do we not need to allocate memory for str first? Can someone
please shed some light on this?
"test" is a string literal. When your compiler constructs your
program, that literal is part of the object file. The pointer str is
initialized with the address of the first 't' in that literal.

While not technically precise, you can think of it conceptually as the
compiler allocating five bytes for the literal; initializing those
five bytes with the values 't', 'e', 's', 't', and '\0'; and
initializing str to point to the start of this five byte area.

To answer your question - when initializing a pointer with a string
literal, you do not need to allocate memory for the pointer because
the compiler did it for you.
Remove del for email
Jul 16 '07 #3
Aarti wrote:
I have a very elementary question about pointers. Please pardon me
for my ignorance of C

int main()
{
int* i;
*i = 1 //at times this may give me a core dump.
const char* str = "test"; //This seems to be a valid construct.
}

Now I understand that when we declare int* i, we just have a pointer
that may point to any place. If we try to store something in it, we
may get a segmentation fault.
Not necessarily. Segmentation faults do occur under modern hardware
and operating systems, but not on all systems. Under DOS, for example,
a segmentation fault will not occur.

But in all cases, attempting to deference an indeterminate pointer
causes Undefined behaviour, as per the C Standard. Also the outcome of
storing an arbitrary numeric value into a pointer, (as you've done
above), is implementation defined. It may be perfectly sensible in one
situation, but fatal in another. It is however, not portable.
But why does const char* str = "test"
work? Do we not need to allocate memory for str first? Can someone
please shed some light on this?

That's because when the implementation compiled your program, it
automatically and anonymously allocated storage space for the string
and initialised str to point to the first element of it. This is a
part of the "high level" nature of languages like C. In assembler, for
example, you'd have to manually set aside storage for "test" and
explicitly initialise the pointer, (or register), with the start
address of this piece of storage.

Jul 16 '07 #4

Aarti wrote:
I have a very elementary question about pointers. Please pardon me
for my ignorance of C

int main()
{
int* i;
*i = 1 //at times this may give me a core dump.
const char* str = "test"; //This seems to be a valid construct.
}

Now I understand that when we declare int* i, we just have a pointer
that may point to any place. If we try to store something in it, we
may get a segmentation fault. But why does const char* str = "test"
work?
"test" is a valid string literal, that means str will be pointing to a
valid pointer.
Where as 'i' is uninitialized and dereferencing 'i' causes undefined
behavior.
Do we not need to allocate memory for str first? Can someone
please shed some light on this?
Yes, 'str' in this case is pointing to a valid (allocated) memory.

Mohan

Jul 16 '07 #5
Mohan <aj****@gmail.comwrote:
Aarti wrote:
int main()
{
int* i;
*i = 1 //at times this may give me a core dump.
const char* str = "test"; //This seems to be a valid construct.
}
"test" is a valid string literal, that means str will be pointing to a
valid pointer.
str points to the first character of an array of characters. It does
not point to a pointer.

--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gmail.com | don't, I need to know. Flames welcome.
Jul 16 '07 #6
Christopher Benson-Manica wrote:
>
Mohan <aj****@gmail.comwrote:
Aarti wrote:
int main()
{
int* i;
*i = 1 //at times this may give me a core dump.
const char* str = "test";
>//This seems to be a valid construct.
}
"test" is a valid string literal,
that means str will be pointing to a
valid pointer.

str points to the first character of an array of characters. It does
not point to a pointer.
You can also say that str is a pointer to a string.

--
pete
Jul 16 '07 #7
On Mon, 16 Jul 2007 00:56:11 -0700, santosh <sa*********@gmail.com>
wrote:
>Aarti wrote:
>I have a very elementary question about pointers. Please pardon me
for my ignorance of C

int main()
{
int* i;
*i = 1 //at times this may give me a core dump.
const char* str = "test"; //This seems to be a valid construct.
}

Now I understand that when we declare int* i, we just have a pointer
that may point to any place. If we try to store something in it, we
may get a segmentation fault.

Not necessarily. Segmentation faults do occur under modern hardware
and operating systems, but not on all systems. Under DOS, for example,
a segmentation fault will not occur.

But in all cases, attempting to deference an indeterminate pointer
causes Undefined behaviour, as per the C Standard. Also the outcome of
storing an arbitrary numeric value into a pointer, (as you've done
above), is implementation defined. It may be perfectly sensible in one
situation, but fatal in another. It is however, not portable.
He was not attempting to store a numeric value into the pointer, but
into the object the pointer should have been pointing to.
>
> But why does const char* str = "test"
work? Do we not need to allocate memory for str first? Can someone
please shed some light on this?


That's because when the implementation compiled your program, it
automatically and anonymously allocated storage space for the string
and initialised str to point to the first element of it. This is a
part of the "high level" nature of languages like C. In assembler, for
example, you'd have to manually set aside storage for "test" and
explicitly initialise the pointer, (or register), with the start
address of this piece of storage.

Remove del for email
Jul 17 '07 #8
On Mon, 16 Jul 2007 10:42:13 -0000, Mohan <aj****@gmail.comwrote:
>
Aarti wrote:
>I have a very elementary question about pointers. Please pardon me
for my ignorance of C

int main()
{
int* i;
*i = 1 //at times this may give me a core dump.
const char* str = "test"; //This seems to be a valid construct.
}

Now I understand that when we declare int* i, we just have a pointer
that may point to any place. If we try to store something in it, we
may get a segmentation fault. But why does const char* str = "test"
work?

"test" is a valid string literal, that means str will be pointing to a
valid pointer.
str will be pointing to a valid char.
>Where as 'i' is uninitialized and dereferencing 'i' causes undefined
behavior.
>Do we not need to allocate memory for str first? Can someone
please shed some light on this?
Yes, 'str' in this case is pointing to a valid (allocated) memory.

Mohan

Remove del for email
Jul 17 '07 #9
<snip>
"test" is a valid string literal, that means str will be pointing to a
valid pointer.

str points to the first character of an array of characters. It does
not point to a pointer.
Yes, you are correct. Thanks for correcting me.

Mohan

Jul 17 '07 #10
On Mon, 16 Jul 2007 10:42:13 -0000 Mohan wrote:

[Quoting Mohan as my server no longer carries the OP]
Aarti wrote:
I have a very elementary question about pointers. Please pardon me
for my ignorance of C

int main()
{
int* i;
*i = 1 //at times this may give me a core dump.
const char* str = "test"; //This seems to be a valid construct.
}

Now I understand that when we declare int* i, we just have a pointer
that may point to any place. If we try to store something in it, we
may get a segmentation fault. But why does const char* str = "test"
work?
I think you are confusing things due to different notations.

You have:
int* i;
*i = 1;

This is not correct, as i is not properly initialised so dereferencing it on
the second line causes undefined behaviour.

What you have above, is *NOT* the same as:
int* i = 1;
Here you create a pointer to an int and make it point to the address "1",
not defining the content of *i.

Had you written:
char* str;
*str = "test";
you would have had the same problem (plus an additional one), you would
have dereferenced the uninitialized pointer to char str. (And even had it
been initialised, it would be a syntax error to assign as string literal to
it).

Writing:
char* str;
str = "test";
would be correct and do the same thing as your example, but then
int* i;
i = 1;
would also be valid (and do the same as int *i=1;) but not do what you
tried.

The fact that the legal construct 'int *i=1;' contains the sequence '*i=1;'
does not mean that i is dereferenced, the * belongs to the declaration of i.

I imagine that this might have confused you.

Cheers
/urs

--
"Change is inevitable, except from a vending machine."
-- Urs Beeli, <usenet@CONCAT_MY_FIRST_AND_LAST_NAME.ch>
Jul 17 '07 #11
Urs Beeli wrote:
I think you are confusing things due to different notations.

You have:
int* i;
*i = 1;

This is not correct, as i is not properly initialised so dereferencing it on
the second line causes undefined behaviour.

What you have above, is *NOT* the same as:
int* i = 1;
Here you create a pointer to an int and make it point to the address "1",
not defining the content of *i.
Here you have a constraint violation. `1` is not a legal value for a
pointer. (If you cast the integer to a pointer, only the implementation
knows what will happen. I think it has to tell you, though.)

--
Hewlett-Packard Limited registered no:
registered office: Cain Road, Bracknell, Berks RG12 1HN 690597 England

Jul 17 '07 #12
On Tue, 17 Jul 2007 13:35:38 +0100 Chris Dollin wrote:
Urs Beeli wrote:
I think you are confusing things due to different notations.

You have:
int* i;
*i = 1;

This is not correct, as i is not properly initialised so dereferencing it on
the second line causes undefined behaviour.

What you have above, is *NOT* the same as:
int* i = 1;
Here you create a pointer to an int and make it point to the address "1",
not defining the content of *i.

Here you have a constraint violation. `1` is not a legal value for a
pointer. (If you cast the integer to a pointer, only the implementation
knows what will happen. I think it has to tell you, though.)
Fair enough, I missed that in my zeal to unconfuse the OP :)

Cheers
/urs

--
"Change is inevitable, except from a vending machine."
-- Urs Beeli, <usenet@CONCAT_MY_FIRST_AND_LAST_NAME.ch>
Jul 17 '07 #13
On Jul 15, 10:14 pm, Aarti <aarti.sa...@gmail.comwrote:
int main()
{
int* i;
*i = 1 //at times this may give me a core dump.
const char* str = "test"; //This seems to be a valid construct.

}
Shouldn't there be a semicolon on line 4?

1: int main()
2: {
3: int* i;
4: *i = 1; //at times this may give me a core dump.
5: const char* str = "test"; //This seems to be a valid construct.
6:
7: }

Jul 17 '07 #14

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

Similar topics

54
by: seberino | last post by:
Many people I know ask why Python does slicing the way it does..... Can anyone /please/ give me a good defense/justification??? I'm referring to why mystring gives me elements 0, 1, 2 and 3...
56
by: Dave Vandervies | last post by:
I just fixed a bug that some of the correctness pedants around here may find useful as ammunition. The problem was that some code would, very occasionally, die with a segmentation violation...
9
by: kathy | last post by:
I am using std::vector in my program: func() { std::vector <CMyClass *> vpMyClass; vpMyClass.push_back(new CMyClass()); vpMyClass.push_back(new CMyClass()); vpMyClass.push_back(new...
9
by: pauldepstein | last post by:
#include <iostream> using namespace std; int main() { int testNum; char *ptr; testNum = 1; ptr = (char*)(&testNum);
4
by: MikeB | last post by:
I've been all over the net with this question, I hope I've finally found a group where I can ask about Visual Basic 2005. I'm at uni and we're working with Visual Basic 2005. I have some books, ...
2
by: CAM | last post by:
Hello, I am wondering if someone can give me some pointers. Currently I am using Access 2002 I developed an inventory tracking database, which this database is used in California and in...
23
by: TefJlives | last post by:
Hi all, I'm learning a bit about C, and I have a few questions. I'm not trying to insult C or anything with these questions, they're just honestly things I don't get. It seems like pointers...
6
by: Simon Walsh | last post by:
I'm an Electronics student in college and I'm currently working on a project. I was given a circuit diagram for my project, from which I had to design a printed circuit board to be sent off and...
28
by: Randy Reimers | last post by:
(Hope I'm posting this correctly, otherwise - sorry!, don't know what else to do) I wrote a set of programs "many" years ago, running in a type of basic, called "Thoroughbred Basic", a type of...
6
by: jmDesktop | last post by:
In a function that takes another function (function pointer) as a argument, or the callback function, which is the one that "calls back"? I'm having a hard time understanding the language. Am I...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
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,...
0
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...
0
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,...
0
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...
0
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...
0
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,...

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.