473,503 Members | 11,783 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Doubt about pass pointer to int.

Hello,

The output of the code below is:
number = 10
number = 0 (or other number except 15)

Why the output of the second 'number' is not 15? Why the 'number' address is
not changed?

Thanks in advance, Vinicius.
#include <stdio.h>
#include <stdlib.h>

void change_int(int *num);

int main(void)
{
int *number;

number = (int *) malloc(sizeof(int));
*number = 10;
printf("number = %d\n", *number);
change_int(number);
printf("number = %d\n", *number);

free(number);
system("PAUSE");
return 0;
}

void change_int(int *num)
{
int *temp;

temp = num;
num = (int *) malloc(sizeof(int));
*num = 15;
free(temp);
}
Nov 14 '05 #1
5 1472
CViniciusM wrote:
Hello,

The output of the code below is:
number = 10
number = 0 (or other number except 15)

Why the output of the second 'number' is not 15? Why the 'number' address is
not changed?
Well, since you've invoked undefined behavior in your code, *anything*
could have happened. See below.

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

void change_int(int *num);

int main(void)
{
int *number;

number = (int *) malloc(sizeof(int)); Better:
number = malloc(sizeof *number);
if (number == NULL) {
puts("Allocation of `number' failed.");
exit(EXIT_FAILURE);
} *number = 10;
printf("number = %d\n", *number);
change_int(number); Remember, the value of `number', a pointer to int, is passed to the
function change_int().

First see the comments in the function change_int() below, then come
back here. printf("number = %d\n", *number);
OK, you're back. ;-)

Whoops. `number' no longer points to valid memory, as it has been freed
in change_int(). You have now invoked undefined behavior.
free(number); Double whoops. You've now freed the same memory twice. UB again! system("PAUSE");
return 0;
}

void change_int(int *num)
{
int *temp;

temp = num; `temp' now points to the same int as `number' in main(). num = (int *) malloc(sizeof(int)); Better:
num = malloc( sizeof *num);
if (num == NULL) {
puts("allocation of `num' in `change_int' failed");
exit(EXIT_FAILURE);
} *num = 15; `num' now points to memory containing the int 15. free(temp); The memory originally allocated to `number' in main() is freed.
*And*, since `num' now goes out of scope, the memory allocated to it can
no longer be referenced. MEMORY LEAK! }


Remember, in C, parameters are /passed by value/. If you want to side
effect a parameter, you need to pass a pointer to it.

HTH,
--ag
--
Artie Gold -- Austin, Texas

"Yeah. It's an urban legend. But it's a *great* urban legend!"
Nov 14 '05 #2
On 29 Feb 2004 14:04:49 -0800, cv********@uol.com.br (CViniciusM) wrote:
Hello,

The output of the code below is:
number = 10
number = 0 (or other number except 15)

Why the output of the second 'number' is not 15? Why the 'number' address is
not changed?

Thanks in advance, Vinicius.
When dealing with dynamic memory allocation, keep in mind that each call to
malloc() should be balanced by exactly one call to free(), passing free()
the value obtained from the malloc() call. With that in mind...


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

void change_int(int *num);

int main(void)
{
int *number;

number = (int *) malloc(sizeof(int));
*number = 10;
printf("number = %d\n", *number);
change_int(number);
printf("number = %d\n", *number);
free(number);
This should either be the first time the value in number is being passed to
free() (it isn't), or the first time you've made an attempt to free
whatever dynamically-allocated pointer is currently in number (that isn't
the case, either.)
system("PAUSE");
return 0;
}

void change_int(int *num)
{
int *temp;

temp = num;
At this point both temp /and/ num point to the int you're presumably trying
to change...
num = (int *) malloc(sizeof(int));
But now you have overwritten the address of that int in num with the
address of a new, dynamically allocated piece of memory. BTW, don't bother
to cast, it isn't necesesary in C:

num = malloc(sizeof(int));
*num = 15;
You are now setting the value of the dynamically allocated int you just
obtained in the previous statement.
free(temp);
You've just freed the dynamic memory that you allocated in main() (pointed
to by "number" there), and on top of that, the memory pointed to by "num"
has just been leaked (you've lost that pointer, never to be regained)
}


So, think about all that and give it another shot...
Good luck,
-leor
Leor Zolman
BD Software
le**@bdsoft.com
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #3
fix


CViniciusM wrote:
Hello,

The output of the code below is:
number = 10
number = 0 (or other number except 15)

Why the output of the second 'number' is not 15? Why the 'number' address is
not changed?

Thanks in advance, Vinicius.
#include <stdio.h>
#include <stdlib.h>

void change_int(int *num);

int main(void)
{
int *number;

number = (int *) malloc(sizeof(int));
*number = 10;
printf("number = %d\n", *number);
change_int(number);
printf("number = %d\n", *number);

free(number);
system("PAUSE");
return 0;
}

void change_int(int *num)
{
int *temp;

temp = num;
num = (int *) malloc(sizeof(int));
*num = 15;
free(temp);
Just a newbie to C, but I guess this line is the problem.
temp and num is pointing to the same allocated memory,
you free temp means you free num,
and then num is now pointing to some unknown stuffs.
}


Nov 14 '05 #4
CViniciusM wrote:
Hello,

The output of the code below is:
number = 10
number = 0 (or other number except 15)

Why the output of the second 'number' is not 15? Why the 'number' address
is not changed?

Thanks in advance, Vinicius.
#include <stdio.h>
#include <stdlib.h>

void change_int(int *num);

int main(void)
{
int *number;

number = (int *) malloc(sizeof(int));
The cast is unnecessary.

Check that malloc succeeded before relying on its return value for storage
purposes. (If it failed, it will return NULL.)
*number = 10;
printf("number = %d\n", *number);
change_int(number);
printf("number = %d\n", *number);

free(number);
system("PAUSE");
On my system, this call issues the message:

PAUSE: command not found
return 0;
}

void change_int(int *num)
{
int *temp;

temp = num;
num = (int *) malloc(sizeof(int));
*num = 15;
free(temp);
}


C is a pass-by-value language. Your change_int function does this:

1) save a pointer to your sizeof(int) bytes, using temp.
2) allocate some fresh memory, using a local variable (yes, num is local to
change_int -- it's just a *copy* of the original pointer from main(), and
will be destroyed on exit).
3) assign 15 to the storage thus allocated (assuming the allocation request
didn't fail).
4) give up the memory you originally allocated in main().
5) return, in the course of which all local objects are destroyed, including
your one-and-only pointer to the new block of memory.

When you get back to main(), you printf("%d\n", *number) - BUT the memory
that this pointer pointed to was freed in change_int(). So the access is
invalid.

Your change_int() function can be rewritten very simply:

void change_int(int *num)
{
*num = 15;
}

Try it and see. :-)

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #5
fix wrote:


CViniciusM wrote:
void change_int(int *num)
{
int *temp;

temp = num;
num = (int *) malloc(sizeof(int));
*num = 15;
free(temp);


Just a newbie to C, but I guess this line is the problem.
temp and num is pointing to the same allocated memory,
you free temp means you free num,


No, because num has acquired a new value by that time. You are, however,
right in thinking that this function has BIG problems. :-)

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #6

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

Similar topics

110
9812
by: Mr A | last post by:
Hi! I've been thinking about passing parameteras using references instead of pointers in order to emphasize that the parameter must be an object. Exemple: void func(Objec& object); //object...
9
4964
by: grid | last post by:
Hi, I have a function which takes a variable number of arguments.It then calls va_start macro to initialize the argument list.But here in my case I have a special builtin va_start provided by the...
2
1396
by: Priya Mishra | last post by:
Hi Everybody Well I saw one open source code, Which is written in C++ in this code i came across very unusall style of coding I am bit fixed on this, please any one from you all help me. I...
28
1888
by: dutche | last post by:
Hi, there is some kind of difference in these two statements? float num = 154.87; printf("There is : $0.0f",num); and float num = 154.87;
8
2382
by: toton | last post by:
HI, One more small doubt from today's mail. I have certain function which returns a pointer (sometimes a const pointer from a const member function). And certain member function needs reference...
4
2273
by: Jon Slaughter | last post by:
I'm reading a book on C# and it says there are 4 ways of passing types: 1. Pass value type by value 2. Pass value type by reference 3. Pass reference by value 4. Pass reference by reference. ...
11
3333
by: venkatagmail | last post by:
I have problem understanding pass by value and pass by reference and want to how how they are or appear in the memory: I had to get my basics right again. I create an array and try all possible...
5
1724
by: nembo kid | last post by:
In the following function, s shouldn't be a pointer costant (array's name)? So why it is legal its increment? Thanks in advance. /* Code starts here */ void chartobyte (char *s) { while...
4
6654
by: S. | last post by:
Hi all, I have the requirement that I must pass-by-reference to my function addStudent() and getAge() functions where my getAge() function is within the addStudent() function. I am able to...
0
7194
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
7070
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
7316
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...
1
6976
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...
1
4993
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...
0
4666
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...
0
3148
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1495
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 ...
0
372
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.