473,748 Members | 7,590 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(i nt)*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 1619
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(i nt)*4);
If the malloc() call succeeds, you now have this situation
(apologies for the bad ASCII art):

ptr p2 dynamic
+------+ +------+ +---+---+---+---+
| *--------> | *--------> |int|int|int|in t|
+------+ +------+ +---+---+---+---+
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|in t|
+------+ | +------+ +---+---+---+---+
|
+-->
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*********@ya hoo.com> wrote in message
news:58******** *************** ***@posting.goo gle.com...
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(i nt)*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
3410
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 application in Python without using prebuilt numerical libraries and data objects such as dictionaries and lists. I have been experimenting with numerical algorithms in Python with a heavy use of the Numeric module. My experience is that Python...
21
18600
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 probna {
4
6381
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 allocated a set of pointer to pointers as my multi-dimensional arrays. Here is my code (i have omitted checking calloc's return value to make this shorter): int **filter; filter = calloc( ylength, sizeof(int*) ); for( i = 0 ; i < ylength...
7
16536
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
2126
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 meets these requirements, but after reading the chapter on exceptions in 'Exceptional C++':Sutter, I am not sure if its is really Exception safe or Exception Neutral. I suppose putting the theory in that chapter into practice isn't trivial.
8
1581
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 before, and then pass it as func(ptr) instead of func(&ptr), what's the use of the & operator ? Or is this just extra functionality of c. I can ofcourse imagine that you would want to allocate memory within the function itself, in which...
17
5258
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, MAXNSTU+1, 1, MAXCOV+MAXCOVLOC+3); aa = dmatrix(1, MAXNSTU+1, 1, MAXCOV+MAXCOVLOC+3); augin = dmatrix(1, MAXNSTU+1, 1, MAXCOV+MAXCOVLOC+3+MAXSIMS); augout = dmatrix(1, MAXNSTU+1, 1, MAXCOV+MAXCOVLOC+3+MAXSIMS);
6
2525
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 pointer version, else if only use object for a limited scope, then use non-pointer version. Does limited scope means the object is only used in the same function
50
4493
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): //------------------------------------------------------------------ template<typename Data_t> class SmartPointer { Data_t* data; void(*deleterFunc)(Data_t*);
0
8831
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9548
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
9374
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
9325
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
9249
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...
0
8244
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6076
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();...
0
4607
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3315
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

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.