473,625 Members | 2,999 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 6211
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*******@aust in.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(MAGICNUM BER * 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_FAILU RE);
}
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******* *************@n ews.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*sizeo f 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.u ni-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

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

Similar topics

58
10114
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 code... TCHAR myArray; DoStuff(myArray);
4
3013
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) { static FILE *dbg = fopen("pakets.log", "wbc"); if (dbg)
12
5382
by: Mike | last post by:
Consider the following code: """ struct person { char *name; int age; }; typedef struct person* StructType;
7
3296
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 object is a reference type? my code is not proving that. I have a web project i created from a web service that is my object: public class ExcelService : SoapHttpClientProtocol {
0
8253
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8692
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
8635
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8354
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8497
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6116
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
5570
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();...
1
2621
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1802
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.