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

passing an uninitialize pointer

joe
Hi all! I just have quick, possibly stupid question....
is it possible to do the following:

int func(){
int *pointer;

foo(pointer);
}

int foo(int *pointer){
pointer = (int*)malloc(10 * sizeof(int));
}

do I just have the syntax wrong or is this illegal?

Thanks in advance!
Joe
Nov 14 '05 #1
20 6147
joe wrote:
Hi all! I just have quick, possibly stupid question....
is it possible to do the following:

int func(){
int *pointer;

foo(pointer); Since arguments in C are passed by *value*, the variable `pointer'
remains uninitialized at this point. }

int foo(int *pointer){
pointer = (int*)malloc(10 * sizeof(int)); Even worse, all the above line does is introduce a memory leak. }

do I just have the syntax wrong or is this illegal?

The syntax is fine. You don't even invoke undefined behavior.
Unfortunately, outside of the memory leak, it doesn't do *anything*.

A function cannot side effect a parameter (pass-by-value) but it can
side effect what a parameter *points to*.

In this case something like:

void foo(int **pointer) {
*pointer = malloc(10 * sizeof **pointer);
}

int main(void) {
int *pointer;
foo(&pointer);
/* pointer now contains the value returned by
malloc() in foo() */
...
}

HTH,
--ag

--
Artie Gold -- Austin, Texas

"What they accuse you of -- is what they have planned."
Nov 14 '05 #2
"Artie Gold" <ar*******@austin.rr.com> wrote in message
news:2k************@uni-berlin.de...
joe wrote:
Hi all! I just have quick, possibly stupid question....
is it possible to do the following:

int func(){
int *pointer;

foo(pointer);

Since arguments in C are passed by *value*, the variable `pointer'
remains uninitialized at this point.
}

int foo(int *pointer){
pointer = (int*)malloc(10 * sizeof(int));

Even worse, all the above line does is introduce a memory leak.
}

do I just have the syntax wrong or is this illegal?

The syntax is fine. You don't even invoke undefined behavior.


So passing an uninitialised pointer (which must mean accessing it in order
to make a copy) doesn't invoke undefined behaviour?

Alex
Nov 14 '05 #3
joe wrote:
Hi all! I just have quick, possibly stupid question....
is it possible to do the following:

int func(){
int *pointer;

foo(pointer);
}

int foo(int *pointer){
pointer = (int*)malloc(10 * sizeof(int));
}

do I just have the syntax wrong or is this illegal?


This is covered fully in the FAQ. The fact that you cast the return
from malloc as well as asking this question demonstrates that you have
neither followed the newsgroup before posting not checked the FAQ. That
is a usenet sin.

#include <stdlib.h>
#include <stdio.h>

#define MAGICNUMBER 10

int *foo(int **pointer)
{
*pointer = malloc(MAGICNUMBER * sizeof **pointer);
return *pointer;
}

int main(void)
{
int *pointer = 0;
printf("before calling foo, pointer == %p\n", (void *) pointer);
if (!foo(&pointer)) {
fprintf(stderr, "the malloc call failed\n");
exit(EXIT_FAILURE);
}
printf("after calling foo, pointer == %p\n", (void *) pointer);
free(pointer);
return 0;
}

Nov 14 '05 #4
joe <jm*****@NOSPAM.cs.kent.edu> wrote in message news:<20********************@news.kent.edu>...
Hi all! I just have quick, possibly stupid question....
is it possible to do the following:

int func(){
int *pointer;

foo(pointer);
}

int foo(int *pointer){
pointer = (int*)malloc(10 * sizeof(int));
}

do I just have the syntax wrong or is this illegal?

Thanks in advance!
Joe


Try this -

int func(){
int *pointer;

pointer = foo(pointer);
/* If pointer == NULL .. print a error gracefully exit */

}

int *foo(int *pointer){
pointer = malloc(10 * sizeof *pointer );
if ( pointer == NULL )
return NULL;
else
return pointer;
}

Upon finishing usage of pointer don't forget to free ( free(pointer)).

HTH,
- Ravi
Nov 14 '05 #5
ra******@gmail.com (Ravi Uday) wrote:
Try this -
It works, but it is unnecessarily complicated:
int func(){
int *pointer;

pointer = foo(pointer);
/* If pointer == NULL .. print a error gracefully exit */

}

int *foo(int *pointer){
pointer = malloc(10 * sizeof *pointer );
Why pass this pointer in at all, if the first thing you do with it in
the function is to overwrite it? You could just as easily have a local
temporary pointer object.
if ( pointer == NULL )
return NULL;
else
return pointer;


Erm... what does this if statement achieve that a simple

return pointer;

doesn't?

Richard
Nov 14 '05 #6
Hi Alex,

So passing an uninitialised pointer (which must mean accessing it in order
to make a copy) doesn't invoke undefined behaviour?


Nope. You copy the "content" of the pointer, supposedly an address,
to another pointer object but you do not have to read let alone change
the content of the "address".
So, you essentially pass crap to the foo() function of the OP but
this crap is never evaluated; hence, no UB.

Unfortunately, your original crappy pointer does not become initialised,
so you invoke UB when trying to use it.
HTH
Michael

Nov 14 '05 #7
On Sun, 5 Jul 2004, joe wrote:
Hi all! I just have quick, possibly stupid question....
is it possible to do the following:

int func(){
int *pointer;

foo(pointer);
}

int foo(int *pointer){
pointer = (int*)malloc(10 * sizeof(int));
}

do I just have the syntax wrong or is this illegal?


This is completely valid code but I'm guessing it does not do what you
want it to do. Just to keep things a little easier to discuss, here is
your code with different variables:

#include <stdlib.h>

void foo(int *);

int main(void)
{
int *p;
foo(p);
return 0;
}

void foo(int *q)
{
q = malloc(10*sizeof int);
}

First, I #include <stdlib.h> when using malloc. Second, I do not return
anything from foo so it is defined as returning void. Third, I do not cast
the result of malloc, which hides the fact you forgot to #include
<stdlib.h>.

Now, here is an explanation of what the code does:

The first line of main will create a variable called p. This variable will
exist somewhere. The contents of this variable will be some random value.
The second line of main we pass this random value to the function foo.
When we reach the function foo it creates a variable called q and assigns
q with the random value p holds. On the first line of foo we change the
value of q to the memory location returned by malloc. The variable q (not
p) now holds a valid memory location (assuming malloc was successful). I
then return to main. The variable q is now out of scope and disappears.
The memory it points to is lost.

Important thing to note is that at no time was the variable p assigned any
value. You are probably assuming that by altering q, a COPY of p, you are
some how altering p. Not so.

What you need to do is pass in the address of p (&p) and then have foo
accept (int **q). Any change to *q will be a change to p. This is because
q is a pointer to p thus *q is p.

--
Send e-mail to: darrell at cs dot toronto dot edu
Don't send e-mail to vi************@whitehouse.gov
Nov 14 '05 #8
"Michael Mair" <ma********************@ians.uni-stuttgart.de> wrote in
message news:cc**********@infosun2.rus.uni-stuttgart.de...
So passing an uninitialised pointer (which must mean accessing it in
order to make a copy) doesn't invoke undefined behaviour?


Nope. You copy the "content" of the pointer, [...]


Right. My point was that if this assignment invokes undefined behaviour
(which, AFAIK, it does - correct me if I'm wrong):

void func(void) {
int i;
int j = i;
}

Then I don't see why this function call, which conceptually has an assigment
like above, wouldn't:

void foo(int j) { /* nothing */ }

void func(void) {
int i;
foo(i);
}

So, does this call to foo() invoke undefined behaviour? If so, doesn't the
call to foo() in the OP's code also invoke undefined behaviour? And if I'm
wrong please tell me why!

Alex
Nov 14 '05 #9
>> So passing an uninitialised pointer (which must mean accessing it in order
to make a copy) doesn't invoke undefined behaviour?
Nope. You copy the "content" of the pointer, supposedly an address,
to another pointer object but you do not have to read let alone change
the content of the "address".


Using the content of an uninitialized pointer invokes undefined
behavior. Evaluating a floating-point variable containing a trapping
NaN causes undefined behavior. Evaluating a pointer containing a
trapping NaP (Not A Pointer) also causes undefined behavior. For
example:

int main(void)
{
int *p;
p; /* Undefined behavior */
return 0;
}
So, you essentially pass crap to the foo() function of the OP but
this crap is never evaluated; hence, no UB.


The crap *IS* evaluated (passing the pointer to a function). The
crap is not dereferenced, but since it was already evaluated, it's
too late to avoid undefined behavior.

Gordon L. Burditt
Nov 14 '05 #10
Hiho,

So passing an uninitialised pointer (which must mean accessing it in order
to make a copy) doesn't invoke undefined behaviour?


Nope. You copy the "content" of the pointer, supposedly an address,
to another pointer object but you do not have to read let alone change
the content of the "address".

Using the content of an uninitialized pointer invokes undefined
behavior. Evaluating a floating-point variable containing a trapping
NaN causes undefined behavior. Evaluating a pointer containing a
trapping NaP (Not A Pointer) also causes undefined behavior. For
example:

int main(void)
{
int *p;
p; /* Undefined behavior */
return 0;
}

So, you essentially pass crap to the foo() function of the OP but
this crap is never evaluated; hence, no UB.

The crap *IS* evaluated (passing the pointer to a function). The
crap is not dereferenced, but since it was already evaluated, it's
too late to avoid undefined behavior.


Ooops, I solemnly abdicate all evil:

I somehow considered only the stuff about trap representations (6.2.6.1)
and lvalues (6.3.2.1), deducing the wrong thing, but in 6.5.2.2 it
clearly says that arguments are evaluated and their values are assigned
to the corresponding parameter. Shame on me.

Sorry for the misinformation
Michael

Nov 14 '05 #11
Sorry Alex,

wrong train of thinking on my part, see the other posting :-/

Nov 14 '05 #12
On Mon, 05 Jul 2004 13:30:18 GMT, rl*@hoekstra-uitgeverij.nl (Richard
Bos) wrote in comp.lang.c:
ra******@gmail.com (Ravi Uday) wrote:
Try this -


It works, but it is unnecessarily complicated:


Does not.
int func(){
int *pointer;
Uninitialized pointer.
pointer = foo(pointer);


Accessing value of uninitialized object. Undefined behavior.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #13
On 5 Jul 2004 13:30:05 GMT, da*****@NOMORESPAMcs.utoronto.ca.com
(Darrell Grainger) wrote in comp.lang.c:
On Sun, 5 Jul 2004, joe wrote:
Hi all! I just have quick, possibly stupid question....
is it possible to do the following:

int func(){
int *pointer;

foo(pointer);
}

int foo(int *pointer){
pointer = (int*)malloc(10 * sizeof(int));
}

do I just have the syntax wrong or is this illegal?


This is completely valid code but I'm guessing it does not do what you


No, invalid code. Invokes UB by passing the value of an uninitialized
object (pointer) to a function.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #14

"joe" <jm*****@NOSPAM.cs.kent.edu> wrote

int func(){
int *pointer;

foo(pointer);
}

int foo(int *pointer){
pointer = (int*)malloc(10 * sizeof(int));
}

do I just have the syntax wrong or is this illegal?

Others have pointed out that this is technically undefined behaviour, though
on most common platforms it won't cause a crash. It will only crash if
pointers have "trap representations" which could be triggered when you load
garbage (the unitialised pointer) into a pointer register to pass it to
foo(). Don't worry too much about this at your stage.

However as Richard Bos pointed out, what you are doing is pointless. There
is no point passing a parameter in just to overwrite it in the first line.
I suspect you are making this mistake

int func()
{
int *pointer;

foo(pointer);

/* pointer now points to allocated memory, right?
Wrong. C parameters are pass by value. The value of pointer is
copied and passed to foo(). When foo() modifies the parameter, the
variable in func() retains its same old garbage value. */
}

Nov 14 '05 #15
Artie Gold <ar*******@austin.rr.com> wrote:
joe wrote:
Hi all! I just have quick, possibly stupid question....
is it possible to do the following:

int func(){
int *pointer;

foo(pointer); Since arguments in C are passed by *value*, the variable `pointer'
remains uninitialized at this point.
}

int foo(int *pointer){
pointer = (int*)malloc(10 * sizeof(int));

Even worse, all the above line does is introduce a memory leak.
}

do I just have the syntax wrong or is this illegal?

The syntax is fine. You don't even invoke undefined behavior.


Actually it is undefined behaviour to access the value of an
uninitialized variable (in this case, 'pointer').

Also it is UB to call malloc without including <stdlib.h>.
In this case something like:

void foo(int **pointer) {
*pointer = malloc(10 * sizeof **pointer);
}

int main(void) {
int *pointer;
foo(&pointer);
/* pointer now contains the value returned by
malloc() in foo() */
...
}


I'm surprised that nobody has suggested the simpler:

#include <stdlib.h>

int *foo(void)
{
return malloc(10 * sizeof(int));
}
/* ... */
int *pointer = foo();
Nov 14 '05 #16
Jack Klein <ja*******@spamcop.net> wrote in message news:<a8********************************@4ax.com>. ..
On Mon, 05 Jul 2004 13:30:18 GMT, rl*@hoekstra-uitgeverij.nl (Richard
Bos) wrote in comp.lang.c:
ra******@gmail.com (Ravi Uday) wrote:
Try this -


It works, but it is unnecessarily complicated:


Does not.
int func(){
int *pointer;
Uninitialized pointer.
pointer = foo(pointer);


Accessing value of uninitialized object. Undefined behavior.

Ok so..initialize it to NULL..

int *pointer = NULL;

[also as bros pointed out the use of checking of return value inside the
'foo' function is useless]

- Ravi
Nov 14 '05 #17
"Michael Mair" <ma********************@ians.uni-stuttgart.de> wrote in
message news:cc**********@infosun2.rus.uni-stuttgart.de...
Sorry Alex, [...]


No problem :).

Alex
Nov 14 '05 #18
"Old Wolf" <ol*****@inspire.net.nz> wrote in message
news:84**************************@posting.google.c om...

... it is UB to call malloc without including <stdlib.h>.


No, it isn't.

#include <stdio.h>

void *malloc(size_t);

int main(void)
{
int *p = malloc(sizeof *p);
if (p)
{
*p = 42;
printf("%d\n", *p);
}
return 0;
}

--
Peter
Nov 14 '05 #19
On Mon, 05 Jul 2004 13:08:57 -0500, Jack Klein <ja*******@spamcop.net>
wrote:
On Mon, 05 Jul 2004 13:30:18 GMT, rl*@hoekstra-uitgeverij.nl (Richard
Bos) wrote in comp.lang.c:
ra******@gmail.com (Ravi Uday) wrote:

> int func(){
> int *pointer;
Uninitialized pointer.
> pointer = foo(pointer);


Accessing value of uninitialized object. Undefined behavior.


How about this?

int *pointer1;
foo(&pointer1);

void foo(int **pointer)
{
*pointer = malloc(...);
}

I would say that this does not invoke UB (never mind the memory leak)
because the uninitialized pointer1 is never dereferenced. Am I
correct?
--
aib

ISP e-mail accounts are good for receiving spam.
Nov 14 '05 #20
Orhan Kavrakoglu <ga*******@ttnet.net.tr> wrote:
int *pointer1;
foo(&pointer1);

void foo(int **pointer)
{
*pointer = malloc(...);
}

I would say that this does not invoke UB (never mind the memory leak)
because the uninitialized pointer1 is never dereferenced. Am I
correct?


Yup. Moreover, it is never passed _as_ a pointer. Only its address is
passed.

Richard
Nov 14 '05 #21

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

Similar topics

58
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of...
4
by: Timothy Madden | last post by:
Hello everybody ! I have a function in a dll that will write bytes of data in a log file. The function has a local static FILE pointer like this: void VMLogPacket(BYTE *pData, size_t nSize) {...
12
by: Mike | last post by:
Consider the following code: """ struct person { char *name; int age; }; typedef struct person* StructType;
7
by: TS | last post by:
I was under the assumption that if you pass an object as a param to a method and inside that method this object is changed, the object will stay changed when returned from the method because the...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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: 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:
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
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...

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.