• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: malloc in obj-c/cocoa
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: malloc in obj-c/cocoa


  • Subject: Re: malloc in obj-c/cocoa
  • From: Jens Bauer <email@hidden>
  • Date: Sat, 7 Feb 2004 00:39:52 +0100

Hi Ben,

On Saturday, Feb 7, 2004, at 00:02 Europe/Copenhagen, Ben Dougall wrote:

On Friday, February 6, 2004, at 09:47 pm, Casey Fleser wrote:

On Feb 6, 2004, at 3:14 PM, Ben Dougall wrote:

PositionPtr posp;
posp = (PositionPtr) malloc( i ));
while( i >= 0 ) {
*(posp + i) = *(Buffer + i);
i--;
}

Is i initialized here? Even if it is, it looks like you're writing past the end of the buffer you've allocated. You should malloc i+1 unless it is the length of your buffer and not the index of the last byte in which case you should predecrement i before entering your while loop.

yes i is initialised there and yes, one of my attempts did have i+1 - no difference - exactly the same error and backtrace etc, but i've readded the +1 now.


Uhm, and you should always check for a NULL pointer after your malloc.

I'd prefer writing the above code like this:

PositionPtr posp;
register PositionPtr d;
register const ?????? *s; // s should be of the same type as Buffer

posp = (PositionPtr) malloc(i);
if(posp)
{
s = Buffer;
d = posp;
while(i--)
{
*d++ = *s++; // destination = source
}
}


-That's only if the above task is very time consuming; however a shorter way would be:

printf("i:%d\n", i); // if I is negative, you'll most likely get in trouble, so check if it's in range!
posp = (PositionPtr) malloc(i);
if(posp)
{
while(i--)
{
posp[i] = Buffer[i];
}
}



Love,
Jens
_______________________________________________
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: 
 >Re: malloc in obj-c/cocoa (From: Ben Dougall <email@hidden>)

  • Prev by Date: Re: malloc in obj-c/cocoa
  • Next by Date: Re: malloc in obj-c/cocoa
  • Previous by thread: Re: malloc in obj-c/cocoa
  • Next by thread: Re: Optimisation [inlining] of message calls (was Re: Multiple problems caused by changing NSThreadsleepUntilDate interval)
  • Index(es):
    • Date
    • Thread