Re: Malloc()
Re: Malloc()
- Subject: Re: Malloc()
- From: Pete Yandell <email@hidden>
- Date: Tue, 2 Apr 2002 17:21:21 +1000
Jason,
On Tuesday, April 2, 2002, at 04:49 PM, Jason Moore wrote:
Hello all.. Sorry to keep bothering everyone with C questions, but this
one has me totally stumped..
I need to pass some data (in the form of a char* buffer) into a Unix
library function. I'm getting my data from an NSData object using
GetBytes:range:. My problem is that my buffers are not working.
i have:
char *buffer;
buffer = malloc(bufferSize);
NSLog(@"buffer size is: %i", sizeof(buffer));
here is where the problem is. the log output is 'buffer size is: 4',
even when i change the malloc
statement to read buffer = malloc(129) (129 is the size of the buffer i
need in my test case).
When you ask for C to give you sizeof(buffer) you're actually asking it
to give you the size of the variable called buffer. That variable is a
pointer, and pointers on a Mac are 4 bytes long, so it's giving you the
right answer.
What you're actually trying to find is the size of the data that buffer
points to, so you might think that sizeof(*buffer) would work. Not so!
The other thing that you need to know about sizeof is that it is
evaluated at compile time and knows nothing about things like malloc, so
from it's perspective, sizeof(*buffer) is 1 given that buffer is
declared as a pointer to a single character. There is, in fact, no good
way in C to find out the size of a buffer that has previously been
created with malloc...you just have to keep track of it yourself.
As a counterexample, sizeof will do the right thing for statically
allocated data, so if you declare buffer as:
char buffer[129];
then sizeof(buffer) will give you the expected 129 because the compiler
will know the size at compile time when sizeof is evaluated.
Hope that helps!
Pete Yandell
http://pete.yandell.com/
________________________________________________________________________
This email has been scanned for all viruses by the MessageLabs SkyScan
service. For more information on a proactive anti-virus service working
around the clock, around the globe, visit
http://www.messagelabs.com
________________________________________________________________________
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.
References: | |
| >Malloc() (From: Jason Moore <email@hidden>) |