473,394 Members | 1,841 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,394 software developers and data experts.

Help in c pointers


HI

int *p;
*p = 4;

char * msg;
*msg = 'c';

printf("msg is %s",msg);
when i try to pass a value 4 to place what integer pointer p points to
it says seg fault

but for the char pointer it works fine.

Why this behaviour

Help

Feb 28 '06 #1
30 1793

ma***********@gmail.com schrieb:
int *p;
*p = 4;


You have done the greates programming fault when using pointers.
Never use a pointer when it points somewhere!

Better try this:

int * p;

p = (int *) malloc (sizeof(int));

*p = 4;

Feb 28 '06 #2
hi,

Thanx for the quick reply.

In here i am concerned why while using char * i am able to pass value
to it. Even this points to somewhere right.
So while using int * which points somwhere i am not able to pass value
to it but while using the char * i am able to do it . Why???
Thanx in advance

Feb 28 '06 #3
"Zero" <ch********@web.de> wrote in news:1141121017.828706.126940
@e56g2000cwe.googlegroups.com:
ma***********@gmail.com schrieb:
int *p;
*p = 4;
You have done the greates programming fault when using pointers.
Never use a pointer when it points somewhere!


ITYM: Never use a pointer if it does *not* point to anywhere (that is,
never use an uninitialized pointer.
Better try this:

int * p;

p = (int *) malloc (sizeof(int));

*p = 4;


Better not. There is no need to cast the return value of malloc, and
doing so can hide errors. Always, yes *always*, check that malloc
succeeded:

int *p = malloc(sizeof *p);
if ( p ) {
*p = 4;
} else {
/* handle error */
}

Sinan
--
A. Sinan Unur <1u**@llenroc.ude.invalid>
(reverse each component and remove .invalid for email address)

comp.lang.perl.misc guidelines on the WWW:
http://mail.augustmail.com/~tadmc/cl...uidelines.html

Feb 28 '06 #4
Hi,
Thanx

But again why i am able to pass value to char* even if it is not
intialized.

Cheers

Feb 28 '06 #5
if you have a char,
it must be
printf("%c", *msg);

Feb 28 '06 #6
"ma***********@gmail.com" <ma***********@gmail.com> writes:
int *p;
*p = 4;
p is uninitialized. Attempting to dereference it invokes undefined
behavior.
char * msg;
*msg = 'c';
msg is uninitialized. Attempting to dereference it invokes undefined
behavior.
printf("msg is %s",msg);
when i try to pass a value 4 to place what integer pointer p points to
it says seg fault

but for the char pointer it works fine.


Both are possible consequences of undefined behavior.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 28 '06 #7
A.A
Because you 're luck.

Feb 28 '06 #8
"ma***********@gmail.com" <ma***********@gmail.com> writes:
But again why i am able to pass value to char* even if it is not
intialized.


Please read <http://cfaj.freeshell.org/google/>.

If I understand your question, it's because you're invoking undefined
behavior, which can do anything. See the response I posted a few
minutes ago on the "about the array" thread.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 28 '06 #9

ma***********@gmail.com wrote:
Hi,
Thanx

But again why i am able to pass value to char* even if it is not
intialized.


1. I think it is just a coincidence that you are not getting the error
for char *.
2. Maybe your program terminates on line 2 and u never know if there
was a SEG_FAULT in line 4
3. AFAIK chances for seg_fault is more for integers as their size is
larger.

Feb 28 '06 #10
"A.A" <au******@gmail.com> writes:
Because you 're luck.


Ok, *everybody* who's reading this through Google, run, do not walk,
to <http://cfaj.freeshell.org/google/>. Read it. Understand it.
Do this before you post here again. Please.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 28 '06 #11
Hi keith,

Can u recommend me soem of the advance C books. I have gone thru Expert
C programming. Some book on similiar line sbut with multi threading and
algorithms.

Thanx in advance

Cheers
Vishal

Feb 28 '06 #12
ma***********@gmail.com wrote:
int *p;
*p = 4;

char * msg;
*msg = 'c';

printf("msg is %s",msg);
when i try to pass a value 4 to place what integer pointer p points to
it says seg fault

but for the char pointer it works fine.

Why this behaviour


When you start your program imagine your memory looks like

0x65 0x39 0x82 0x87 0x46 0x53 0x72 0x99 0x27 0x34 ... <== garbage

You then say `p' is a pointer to int

0x65 0x39 0x82 0x87 0x46 0x53 0x72 0x99 0x27 0x34 ... <== garbage
`-------------------' <== p, pointing to garbage

and `msg' is a pointer to char

0x65 0x39 0x82 0x87 0x46 0x53 0x72 0x99 0x27 0x34 ... <== garbage
`-------------------' <== msg, pointing to garbage
Apparently the garbage `p' points to is not writable whereas the garbage
`msg' points to is.

--
If you're posting through Google read <http://cfaj.freeshell.org/google>
Feb 28 '06 #13
Yes,

That can explian this scenario.

Thanks a lot.

Cheers
Vishal

Feb 28 '06 #14
Keith Thompson <ks***@mib.org> wrote in
news:ln************@nuthaus.mib.org:
"A.A" <au******@gmail.com> writes:
Because you 're luck.


Ok, *everybody* who's reading this through Google, run, do not walk,
to <http://cfaj.freeshell.org/google/>. Read it. Understand it.
Do this before you post here again. Please.


Too late. The thread has already become worse than useless with insanely
meaningless posts.

Sinan

--
A. Sinan Unur <1u**@llenroc.ude.invalid>
(reverse each component and remove .invalid for email address)
Feb 28 '06 #15
ma***********@gmail.com wrote:
That can explian this scenario.

^^^^ ^^^^

"That"? What are you referring to?
"this"? What are you referring to?

Please read <http://cfaj.freeshell.org/google> before you post again.

--
If you're posting through Google read <http://cfaj.freeshell.org/google>
Feb 28 '06 #16
"ma***********@gmail.com" wrote:

HI

int *p;
*p = 4;

char * msg;
*msg = 'c';

printf("msg is %s",msg);

when i try to pass a value 4 to place what integer pointer p points to
it says seg fault

but for the char pointer it works fine.

Why this behaviour


Neither pointer has been initialized, and both assignments invoke UB. In
your particular case, the address in p happened to be invalid for an int,
and the address in msg happened to be valid for a char, and didn't cause
any noticable effect by overwriting that memory.

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th*************@gmail.com>
Feb 28 '06 #17
On 2006-02-28, Kenneth Brody <ke******@spamcop.net> wrote:
"ma***********@gmail.com" wrote:

HI

int *p;
*p = 4;

char * msg;
*msg = 'c';

printf("msg is %s",msg);

when i try to pass a value 4 to place what integer pointer p points to
it says seg fault

but for the char pointer it works fine.

Why this behaviour


Neither pointer has been initialized, and both assignments invoke UB. In
your particular case, the address in p happened to be invalid for an int,
and the address in msg happened to be valid for a char, and didn't cause
any noticable effect by overwriting that memory.


Incidentally, there's a third instance of undefined behavior here -
anyone know what it is?
Feb 28 '06 #18
"ma***********@gmail.com" wrote:

int *p;
*p = 4;

char * msg;
*msg = 'c';

printf("msg is %s",msg);

when i try to pass a value 4 to place what integer pointer p
points to it says seg fault but for the char pointer it works fine.

Why this behaviour


You were unlucky with the char pointer.

Neither p nor msg points anywhere. Trying to dereference either of
them results in undefined behavior. Undefined behaviour includes
"working". It also includes launching flying pigs.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Also see <http://www.safalra.com/special/googlegroupsreply/>
Feb 28 '06 #19
Jordan Abel wrote:
On 2006-02-28, Kenneth Brody <ke******@spamcop.net> wrote:
"ma***********@gmail.com" wrote:
int *p;
*p = 4;

char * msg;
*msg = 'c';

printf("msg is %s",msg);


Neither pointer has been initialized, and both assignments invoke UB.


Incidentally, there's a third instance of undefined behavior here -
anyone know what it is?


a) `msg' isn't (*) a c-string (a sequence of chars ending in NUL) so
passing it to printf invokes UB.

b) printf doesn't end with a newline nor is followed by a
fflush(stdout); invoking implementation defined behaviour (???)
(*) probably it is -- there probably is a nul between msg and msg+<some
large integer value>.

--
If you're posting through Google read <http://cfaj.freeshell.org/google>
Feb 28 '06 #20
On 2006-02-28, Pedro Graca <he****@dodgeit.com> wrote:
Jordan Abel wrote:
On 2006-02-28, Kenneth Brody <ke******@spamcop.net> wrote:
"ma***********@gmail.com" wrote:
int *p;
*p = 4;

char * msg;
*msg = 'c';

printf("msg is %s",msg);

Neither pointer has been initialized, and both assignments invoke UB.


Incidentally, there's a third instance of undefined behavior here -
anyone know what it is?


a) `msg' isn't (*) a c-string (a sequence of chars ending in NUL) so
passing it to printf invokes UB.


Not quite - msg isn't a valid pointer at all, so the act itself of
passing it to printf invokes UB. It would equally invoke UB if it were a
void * and being passed to a printf %p format.

The value of msg is indeterminate since it is never initialized. Reading
an indeterminate value results in undefined behavior [since it may be a
trap representation]
Feb 28 '06 #21
On Tue, 28 Feb 2006 10:57:43 UTC, "ma***********@gmail.com"
<ma***********@gmail.com> wrote:
Hi keith,

Can u recommend me soem of the advance C books.
I don't know who u is. Why does you ask us if u knows it? Ask
she/he/it
yourself! Maybe u will answer you, maybe not. I've never seen a
message from Mr./Ms./Mrs. u in usenet at all.

I have gone thru Expert C programming. Some book on similiar line sbut with multi threading and
algorithms.


Mr. google is your friend on that question.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!

Feb 28 '06 #22
hum nice ?
yar i dont know why u got error
but i cant give eroor
*p=4
mins u asign a adress of value 4 to p there no address of 4
but in charector every char have a fix address.
so may be because of this u get error for int & not for charector.ok.

Feb 28 '06 #23
CBFalconer wrote:
[...]
Neither p nor msg points anywhere. Trying to dereference either of
them results in undefined behavior. Undefined behaviour includes
"working". It also includes launching flying pigs.


Can demons come out of a flying pig's nose?

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th*************@gmail.com>

Feb 28 '06 #24
pa********@gmail.com writes:
hum nice ?
yar i dont know why u got error
but i cant give eroor
*p=4
mins u asign a adress of value 4 to p there no address of 4
but in charector every char have a fix address.
so may be because of this u get error for int & not for charector.ok.


Please make some effort to write in standard English. Silly
abbreviations like "u" for "you" just make what you write more
difficult to read. We'll gladly make allowances for minor errors,
especially if English isn't your first language, but I can't even
figure out what you mean.

You also need to provide context when you post a followup. Read
<http://cfaj.freeshell.org/google/> to find out how to do this.

(And the original question has already been answered.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 28 '06 #25
Jordan Abel wrote:
On 2006-02-28, Pedro Graca <he****@dodgeit.com> wrote:
Jordan Abel wrote:
On 2006-02-28, Kenneth Brody <ke******@spamcop.net> wrote:
"ma***********@gmail.com" wrote:
> int *p;
> *p = 4;
>
> char * msg;
> *msg = 'c';
>
> printf("msg is %s",msg);

Neither pointer has been initialized, and both assignments invoke UB.

Incidentally, there's a third instance of undefined behavior here -
anyone know what it is?


a) `msg' isn't (*) a c-string (a sequence of chars ending in NUL) so
passing it to printf invokes UB.


Not quite - msg isn't a valid pointer at all, so the act itself of
passing it to printf invokes UB. It would equally invoke UB if it were a
void * and being passed to a printf %p format.


I understand.

But another question gets raised in my head:
What is a valid pointer?
Examples:

char * p; /* p is, for now, an invalid pointer */

p = &p; /* and now??? */
p = (char*)&p; /* and now??? */
p = main;
p = (char*)main;
p = rand();
p = (char*)rand();
--
If you're posting through Google read <http://cfaj.freeshell.org/google>
Feb 28 '06 #26
Pedro Graca <he****@dodgeit.com> writes:
[...]
But another question gets raised in my head:
What is a valid pointer?
Examples:

char * p; /* p is, for now, an invalid pointer */

p = &p; /* and now??? */
p = (char*)&p; /* and now??? */
In the above two cases, p is a valid pointer; it points to the first
byte of p.
p = main;
Illegal. A conversion from a pointer-to-function type to a
pointer-to-object type requires a cast.
p = (char*)main;
Legal (I think), but undefined. The language does not define the
semantics of a conversion from a pointer-to-function type to a
pointer-to-object type.
p = rand();
Illegal. There is no implicit conversion from int to char*; a cast is
required.
p = (char*)rand();


This is legal, but the result of converting an int value to char* is
implementation-defined (except for the special case of a null pointer
constant). The value of p may or may not be valid.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 28 '06 #27
"ma***********@gmail.com" wrote:

Hi,
Thanx

But again why i am able to pass value to char* even if it is not
intialized.

Because what you have done is *wrong* and you get "undefined behavior".
Undefined behavior can range from nasal demons to actually working
occasionally. Undefined behavior means *anything* can happen.

--
+----------------------------------------------------------------+
| Charles and Francis Richmond richmond at plano dot net |
+----------------------------------------------------------------+
Mar 1 '06 #28
[Jordan's comment on passing an invalid pointer to printf inserted]

Keith Thompson wrote:
Pedro Graca <he****@dodgeit.com> writes:


Jordan Abel wrote [edited]:
the act itself of passing an invalid pointer to printf invokes UB.

What is a valid pointer? [snip examples] p = (char*)rand();


This is legal, but the result of converting an int value to char* is
implementation-defined (except for the special case of a null pointer
constant). The value of p may or may not be valid.


So the following code does not invoke UB?

char * p;
p = (char*)rand();
printf("%c\n", p);

.... and removing the assignment does?

char * p;
printf("%c\n", p);
--
If you're posting through Google read <http://cfaj.freeshell.org/google>
Mar 1 '06 #29
Pedro Graca <he****@dodgeit.com> writes:
[Jordan's comment on passing an invalid pointer to printf inserted]

Keith Thompson wrote:
Pedro Graca <he****@dodgeit.com> writes:
Jordan Abel wrote [edited]:
the act itself of passing an invalid pointer to printf invokes UB.
What is a valid pointer? [snip examples] p = (char*)rand();


This is legal, but the result of converting an int value to char* is
implementation-defined (except for the special case of a null pointer
constant). The value of p may or may not be valid.


So the following code does not invoke UB?

char * p;
p = (char*)rand();
printf("%c\n", p);


You need "%p", not "%c". Actually, the "%p" format expects a void*;
you can almost certainly get away with passing a char* instead, but
IMHO it's better style to convert it:

printf("%p\n", (void*)p);

C99 6.3.2.3p5:

An integer may be converted to any pointer type. Except as
previously specified, the result is implementation-defined, might
not be correctly aligned, might not point to an entity of the
referenced type, and might be a trap representation.

The "previously specified" part refers to null pointer constants.
Alignment shouldn't be an issue for char*, but you could still get a
trap representation. If so, evaluating p, whether you then pass the
value to printf() or not, invokes undefined behavior.
... and removing the assignment does?

char * p;
printf("%c\n", p);


That certainly invokes UB, even with "%p".

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Mar 1 '06 #30
>hum nice ?
yar i dont know why u got error
but i cant give eroor
*p=4
mins u asign a adress of value 4 to p there no address of 4
but in charector every char have a fix address.
so may be because of this u get error for int & not for charector.ok.


Even i agree with Keith. Please use some proper English words as this
group is in public domain. Each one here is trying to figure out what
others write and provide a logical solution to it.

Hindi words like 'yar' should not be used here.

Hope you got the point.

Cheers
Vishal

Mar 1 '06 #31

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

Similar topics

4
by: Greg Baker | last post by:
I don't know what standard protocol is in this newsgroup. Am I allowed to post code and ask for help? I hope so.. :) Here's my problem: I am trying problem 127 of the valladolid online...
3
by: Tommy Lang | last post by:
I am working on this project and I need some help/pointers/comments to get me started, I am stuck. The program will be used to store information in an array while it is running. I need to store...
3
by: Josh | last post by:
Howdy i was recently given a program to do. I have to create a 2d matrix with pointers i have the whole idea down with pointers but there is a problem with one of them i have the code written down...
2
by: leo2100 | last post by:
Hi, I need help with this program. The program is supposed to take a text file and identify the words in it, then it should print them and count how many times a word is repeated. At first main...
1
by: ArcInversion | last post by:
Hi, I've been using a javascript script to create a dragon that flies across the page. Anyways, I'd like to make it so when you click the dragon it takes you to a new page. Was wondering if anyone...
23
by: vinod.bhavnani | last post by:
Hello all, I need desperate help Here is the problem: My problem today is with multidimensional arrays. Lets say i have an array A this is a 4 dimensional static array.
9
by: Andreas Vinther | last post by:
I have a small piece of code that compiles but does not perform like I want it to. This code works: ---------------- void *y0; void *y1; void *y2; void *y3;
6
by: M Turo | last post by:
Hi, I was wondering if anyone can help. I'm want to pre-load a 'table' of function pointers that I can call using a its arrayed index, eg (non c code example) pFunc = func_A; pFunc = func_B;
2
by: StevenChiasson | last post by:
For the record, not a student, just someone attempting to learn C++. Anyway, the problem I'm having right now is the member function detAddress, of object controller. This is more or less, your...
5
by: BillGill | last post by:
Ok, I assume this has been asked many times, but I can't seem to come up with a good Google search to find it. I am trying to learn C++. Specifically I have Microsoft Visual C++ 2005 Express...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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...

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.