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 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;
} 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.
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
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
>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;
} 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 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
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. 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. } This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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()):
//...
|
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...
|
by: Bob |
last post by:
Try the following code
class basic
{
public:
virtual void one()=0;
};
class derived1:public basic
{
public:
|
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...
|
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......
| |
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...
|
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...
|
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?
|
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...
|
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;
|
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,...
| |
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...
|
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...
|
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: 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...
|
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...
|
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...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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 ...
| |