473,473 Members | 2,102 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Basic Pointer Question...

Hi CLCers,
I coded a function to allocate memory and i am passing a pointer to the
function. The code is compiling but throws error and closes while
executing. The program is as below:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p;
void mem_fun(int *i);
mem_fun(p);
printf("%d\n",*p);
getch();
return 0;
}

void mem_fun(int *i)
{

printf("%u\n",i);
i=malloc(sizeof(int));
*i=10;
printf("%d\n",*i);
}

Please help in understanding the problem. Advanced thanks.
Cheers
Shan

Nov 15 '05 #1
9 1267

shan_r...@yahoo.com wrote:
Hi CLCers,
I coded a function to allocate memory and i am passing a pointer to the
function. The code is compiling but throws error and closes while
executing. The program is as below:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p;
void mem_fun(int *i);
mem_fun(p);
printf("%d\n",*p);
getch();
return 0;
}

void mem_fun(int *i)
{

printf("%u\n",i);
i=malloc(sizeof(int));
*i=10;
printf("%d\n",*i);
}

Please help in understanding the problem. Advanced thanks.
Cheers
Shan


You are not using pointers correctly. Here's a good website with an
easy to understand explanation of pointers:

http://cslibrary.stanford.edu/

I removed your first printf from the mem_fun() since I had no idea what
you were trying to do.

Here's your code corrected:

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

void mem_fun(int **);

int
main() {

int *p;
mem_fun(&p);
(void)printf("%d\n",*p);
exit(0);
}

void
mem_fun(int **i)
{

*i = malloc(sizeof(int));
if(*i == NULL)
return;
**i = 10;
(void)printf("%d\n",**i);
return;
}

Nov 15 '05 #2
sh*******@yahoo.com wrote:
Hi CLCers,
I coded a function to allocate memory and i am passing a pointer to the
function. The code is compiling but throws error and closes while
executing. The program is as below:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p;
void mem_fun(int *i);
Do not hide your function declarations within other functions.
mem_fun(p);
Let us recapitulate: C passes arguments by value.
You have given no value to p, so making a copy of p for mem_fun
invokes undefined behaviour. From now on, anything can happen,
including your harddisk being formatted.
If you want to change something using a function, you have
to pass its _address_, not the object itself (which will only
copied but not changed).
Note: The address is also passed by value, but this value is
sufficient to do something.
printf("%d\n",*p);
getch();
This function is not defined in standard C.
return 0;
}

void mem_fun(int *i)
{

printf("%u\n",i);
The format specifier for pointers is %p.
If pointers and integers have different sizes, the above may
go wrong.
i=malloc(sizeof(int));
Better:
i = malloc(sizeof *i);
This works even if you change the type to i.

You forgot to check whether malloc() succeeded.
*i=10;
printf("%d\n",*i);
As you work on a copy of a pointer value which expires at the
end of the function, you have produced a memory leak.
}

Please help in understanding the problem. Advanced thanks.


Better:

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

void mem_fun (int **i);

int main (void)
{
int *p = 0;
mem_fun(&p);
if (p)
printf("%p : %d\n", p, *p);
free(p);
getch();
return 0;
}

void mem_fun (int **i)
{
*i = malloc(sizeof **i);
if (*i)
**i = 10;
else {
fprintf(stderr, "mem alloc trouble\n");
exit(EXIT_FAILURE); /* Replace by _real_ error
** handling whenever possible */
}
}

As you see, I check _twice_ whether malloc() succeeded to be
on the safe side. This is because mem_fun() does not directly
tell me whether it was successful. You may consider returning
*i/int * to signal success or failure.
In addition, as malloc() is hidden within a function, free()
can be easily forgotten.
It is usually better to malloc() on the same "level" as you free()
or to provide companion functions to be called from the same
level performing malloc() and free().
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 15 '05 #3
Hi Guys,
Thanks for your reply. Now i understand what the problem is. When
coding with pointers, i stumble a lot, even though i know that values
are passed to C functions. Thanks again for your time for clearing my
doubt.
Cheers
Shan

Nov 15 '05 #4

Michael Mair wrote:

<snip>
Better:

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

void mem_fun (int **i);

int main (void)
{
int *p = 0;
mem_fun(&p);
if (p)
printf("%p : %d\n", p, *p);


typo? printf("%p : %d\n",(void *) p, *p);

Krishanu

Nov 15 '05 #5
>Better:
#include<stdio.h>
#include<stdlib.h>
void mem_fun (int **i);
int main (void)
{
int *p = 0; hi,Michael
maybe "int *p = (void *)0; " is better than "int *p = 0; ".
and, I always use NULL to initilize a pointer. do you think it's a good
style?
Is the macro "NULL" a standard C's definition?
any word would be appreciated. mem_fun(&p);
if (p)
printf("%p : %d\n", p, *p);
free(p);
getch();
return 0;


}

Nov 15 '05 #6

ke******@hotmail.com wrote:
Better:
#include<stdio.h>
#include<stdlib.h>


void mem_fun (int **i);


int main (void)
{
int *p = 0;

hi,Michael
maybe "int *p = (void *)0; " is better than "int *p = 0; ".


No, both are same.
and, I always use NULL to initilize a pointer. do you think it's a good
style?
Is the macro "NULL" a standard C's definition?
any word would be appreciated.


Did you read FAQs?

http://www.eskimo.com/~scs/C-faq/q5.4.html

Krishanu

--
"Be nice to nerds. Chances are you'll end up working for one."
--Bill Gates

Nov 15 '05 #7
ke******@hotmail.com wrote:
maybe "int *p = (void *)0; " is better than "int *p = 0; ".
and, I always use NULL to initilize a pointer. do you think it's a good
style?
Is the macro "NULL" a standard C's definition?
any word would be appreciated.


Look up Q 5.4 in the FAQ. I would also recommend to read the whole
section 5, which deals with NULL pointers. The FAQ can be found at
http://www.eskimo.com/~scs/C-faq/top.html. It used to be anyway; I
couldn't connect to that site today :(

Peter

Nov 15 '05 #8
Krishanu Debnath wrote:
Michael Mair wrote:

<snip>
Better:

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

void mem_fun (int **i);

int main (void)
{
int *p = 0;
mem_fun(&p);
if (p)
printf("%p : %d\n", p, *p);

typo? printf("%p : %d\n",(void *) p, *p);


True. Thanks.

Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 15 '05 #9
Here's your code corrected:
I dont think so !!!
#include <stdio.h>
#include <stdlib.h>

void mem_fun(int **);

int
main() {

int *p;
mem_fun(&p);
(void)printf("%d\n",*p);
exit(0);
}

void
mem_fun(int **i)
{

*i = malloc(sizeof(int));
if(*i == NULL)
return;
**i = 10;
(void)printf("%d\n",**i);
return; what you are returning and why ? Check your declaration. }


Nov 15 '05 #10

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

Similar topics

6
by: soni29 | last post by:
hi, i'm reading a c++ book and noticed that the author seems to allocate memory differently when using classes, he writes: (assuming a class called CBox exists, with member function size()): //...
41
by: Psykarrd | last post by:
I am trying to declare a string variable as an array of char's. the code looks like this. char name; then when i try to use the variable it dosn't work, however i am not sure you can use it...
1
by: Bob | last post by:
Try the following code class basic { public: virtual void one()=0; }; class derived1:public basic { public:
6
by: pauldepstein | last post by:
I am reading Grimshaw and Ortega's "C++ and Numerical Methods." They construct a vector class which contains the variable vec, a float* variable where the length of the array (number of...
3
by: Chris Mantoulidis | last post by:
I never liked pointers really much, so I decided to stay away from them for a while. I know they're useful, so now I decided to actually learn how the work, use them, etc. Here's my question......
18
by: steve | last post by:
I'm trying to create a structure of three pointers to doubles. For which I have: typedef struct { double *lst_t, *lst_vc, *lst_ic; } last_values; I then need to allocate space for...
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...
6
by: kathy | last post by:
I have a pointer: MyClass *p = NULL; p = new MyClass(...); .... delete p; After delete p, does p equal NULL(it is in C++ standard?)? How to decide if p has been deleted?
13
by: Aarti | last post by:
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...
9
by: Peskov Dmitry | last post by:
It is a very basic question.Surely i got something wrong in my basic understanding. //Contents of file1.cpp using namespace std; #include <iostream> template <typename T> class my_stack;
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...
1
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...
1
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
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
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
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 ...

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.