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

Pointer to Pointer & Mem allocation

Hi,

I'm a bit confused about something, hopefully someone can put me
straight.

I'd like to be able to call a function which takes a pointer to
pointer, have that function allocate memory and return the size. I
can't get it to work and I would like to know why this code outputs
wierd values (the first mem address is ok i think):
int f3(int **ptr)
{
*ptr = malloc(sizeof(int)*4);
printf("%p\n", *ptr);
*ptr++;
printf("%p\n", *ptr);
*ptr++;
printf("%p\n", *ptr);
}

int main(void)
{
int *p2;
f3(&p2);
return 0;
}

The output is:

0xa040448
0x0
0x22f40

:-S Thanks for reading.
Nov 14 '05 #1
2 1594
Yossarian wrote:
Hi,

I'm a bit confused about something, hopefully someone can put me
straight.

I'd like to be able to call a function which takes a pointer to
pointer, have that function allocate memory and return the size. I
can't get it to work and I would like to know why this code outputs
wierd values (the first mem address is ok i think):
int f3(int **ptr)
{
*ptr = malloc(sizeof(int)*4);
If the malloc() call succeeds, you now have this situation
(apologies for the bad ASCII art):

ptr p2 dynamic
+------+ +------+ +---+---+---+---+
| *--------> | *--------> |int|int|int|int|
+------+ +------+ +---+---+---+---+
printf("%p\n", *ptr);
(Side-issue: This isn't quite right. The "%p" specifier
requires a `void*' pointer value, and you're giving it an
`int*' instead. On many machines you will get away with this
error, but for correctness write `(void*)*ptr' instead.)
*ptr++;
Here's the crux: I don't think you understand what this
statement accomplishes. It says "Fetch the value at `*ptr'
(the contents of the second box above), ignore them, and
then advance `ptr' itself by one `int*' position." Now you
have

ptr p2 dynamic
+------+ +------+ +---+---+---+---+
| *-----+ | *--------> |int|int|int|int|
+------+ | +------+ +---+---+---+---+
|
+-->
printf("%p\n", *ptr);
You are now in a serious state of error. You are trying
to print the value `ptr' points at, but it no longer points
at anything useful. It is legal to form a "one past the end"
pointer, but it is not legal to try to access the memory at
that position. There might not even *be* any memory at that
position, and even if there is you have never stored a value
there. So when you try to access the uninitialized value in
a region of memory that might not even exist, all bets are
off and anything at all might happen.
*ptr++;
"Fetch the pointed-to value, ignore it, and advance `ptr'
again." Once again you commit the error of fetching a value
that hasn't been initialized and might not even exist, and
then you add a new error: A "one past the end" pointer is
legal, but a "two past the end" pointer is not. Things just
get worse.
printf("%p\n", *ptr);
}

int main(void)
{
int *p2;
f3(&p2);
return 0;
}

The output is:

0xa040448
0x0
0x22f40


As I hope you now understand, the fact that you got any
output at all is more by good luck than good management. I
suggest you review Question 4.3 in the comp.lang.c Frequently
Asked Questions (FAQ) list

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

In fact, reviewing all of Sections 4, 6, and 7 might be a
good idea.
--
Er*********@sun.com

Nov 14 '05 #2
"Yossarian" <yo*********@yahoo.com> wrote in message
news:58**************************@posting.google.c om...
Hi,

I'm a bit confused about something, hopefully someone can put me
straight.

I'd like to be able to call a function which takes a pointer to
pointer, have that function allocate memory and return the size. I
can't get it to work and I would like to know why this code outputs
wierd values (the first mem address is ok i think):
int f3(int **ptr)
If you're returning the allocated size, the return
type should be 'size_t'.
{
*ptr = malloc(sizeof(int)*4);
You should check here that 'malloc()' succeeded,
and take appropriate action if it did not.
printf("%p\n", *ptr);
*ptr++;
This dereferences the pointer 'ptr', yeilding the address
returned by 'malloc()', discards that value, and then
increments 'ptr' (which makes it point to memory not
'owned' by your program -- i.e. 'ptr' represents a
single pointer, not an array of them. After the above
increment, another *ptr will give 'undefined behavior.)

If you want to 'step through' the addresses of the
allocated 'int' objects:

(*ptr)++;

(this dereferences 'ptr', yeilding the value returned
by 'malloc()', then increments that (pointer) value,
giving it the address of the second allocated 'int'.)

But note that this statement also 'throws away' the value
returned by 'malloc()', preventing you from freeing the memory
later -- a 'memory leak' (unless you either save the original
pointer somewhere or keep track of how many times you increment
*ptr, and use that info to recalculate the original pointer value
returned by 'malloc()'.

If this is not what you're after, please clarify.

(and if I've somehow erred with my explanation,
someone will be sure to point it out. :-))

-Mike
printf("%p\n", *ptr);
*ptr++;
printf("%p\n", *ptr);
}

int main(void)
{
int *p2;
f3(&p2);
return 0;
}

The output is:

0xa040448
0x0
0x22f40

:-S Thanks for reading.

Nov 14 '05 #3

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

Similar topics

44
by: Carl | last post by:
"Nine Language Performance Round-up: Benchmarking Math & File I/O" http://www.osnews.com/story.php?news_id=5602 I think this is an unfair comparison! I wouldn't dream of developing a numerical...
21
by: Roman Werpachowski | last post by:
I can't understand this: double * x = new double; const double * p = x; delete p; works. Why am I allowed to delete a const pointer? On the same note: why am I allowed to do this: class...
4
by: entitledX | last post by:
Hi, I'm trying to use the HDF library to read a few HDF files that I need to process. The data in each file varies in rows, but the columns remain constant. Because of that, I had dynamically...
7
by: morz | last post by:
i just search for a while in c++ groups but cannot find good answer. i have code like this: int **ptr; ptr = new char *; ptr = new int(5); ptr = new int(16);
3
by: Nindi73 | last post by:
Hi, I am in need of a deep copy smart pointer (Boost doesn't provide one) which doesnt require the contained types to have a virtual copy constructor. I wrote a smart pointer class that I think...
8
by: Alef.Veld | last post by:
Just wondering, I sometimes use or see &ptr when passing it through a function so that this specific function works with the actual pointer passed. But if we just allocate memory to this pointer...
17
by: Ivan K. | last post by:
I am looking at some legacy code, which begins by allocating a double matrix with the dmatrix() function from NRC as follows: double **A, **augin, **augout, **aa; A = dmatrix(1,...
6
by: worlman385 | last post by:
For pointer and non-pointer initialization of an object like MyCar mycar; MyCar* mycar = new MyCar(); I heard from other people saying if object i create must live outside scape, then I use...
50
by: Juha Nieminen | last post by:
I asked a long time ago in this group how to make a smart pointer which works with incomplete types. I got this answer (only relevant parts included): ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
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
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...

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.