where is the 'size' for a pointer is allocated in the heap - size

This error happens at the end of the program when I try to free() a pointer
Error in `./out': corrupted size vs. prev_size: 0x3ad1aa70
======= Backtrace: =========
/lib/i386-linux-gnu/libc.so.6(+0x67377)[0xf7556377]
/lib/i386-linux-gnu/libc.so.6(+0x6d2f7)[0xf755c2f7]
/lib/i386-linux-gnu/libc.so.6(+0x6e48a)[0xf755d48a]
./vx_tutorial_exe(main+0x12b2)[0x808533f]
/lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xf7)[0xf7507637]
I think some other pointer is going out of bounds somewhere and deleting the size of my pointer in the heap.
If I can find the address of the heap record for the pointer, i guess I can put a hw watchpoint and find who's doing it
Any ideas ?

Related

why memory for primitive data types is not allocated? [duplicate]

This question already has answers here:
What and where are the stack and heap?
(31 answers)
Closed 8 years ago.
Primitive data types such as char, bool and int have some memory. Suppose char, which has 1 byte of memory. When we use a char variable in our code, then the variable must require 1 byte of memory. Why don't we allocate memory in this case. And as we never allocate memory for it, how does it use the memory ,i.e. Is the CPU allocate memory for it in this case.Also I read somewhere that the primitive data types are put on stack and removed when the work is done for it. What kind of stack? How does the stack comes into picture in this case?
When we create an NSString * variable, we don't allocate the memory for this either.
We only allocate memory when alloc is called, either directly by us or inside a method we call.
An NSString object exists on the heap in memory we've allocated, but the NSString * variable (which is, a pointer to an NSString object) exists in memory on the stack which we do not allocate.
For example, given these two variables:
NSString *stringOne;
NSString *stringTwo;
So far, neither has been allocated any memory on the heap, although they do exist in memory in the exact same way a char, BOOL, or int exists in memory.
NSString *stringOne = [[NSString alloc] initWithString:#"Hello world"];
NSString *stringTwo = stringOne;
Now what has happened? We allocated some memory on the heap for an NSString object. We then initialized this memory to represent the string "Hello world" and then returned a pointer to this object and assigned it to stringOne.
Next, we simply copied that pointer over into the stack memory we're using for stringTwo. We didn't allocate any extra memory on the heap. We simply made our two string variable point to the same allocated memory on the heap.
The question and answer jsd linked in the comments has more explanation on stack and heap memory which will answer some of your questions.
It's also worth noting that a lot of other programming languages such as C++ allow objects to be created on the stack, in which case we don't allocate them, as we would with heap objects. They do exist in memory, just more similarly to primitive data types.
At the risk of being over simplistic, there are three classes of memory for data: 1) static, 2) stack 3) heap.
They are allocated in different ways.
if you have
static char something ;
defined in a function or
char something ;
outside of a function, that data is defined by the linker using instructions from the compiler and allocated by the program loaders.
Nearly every processor in existence uses a stack to support nested data (e.g., function calls). The stack is a block of memory that exists for every process (and for every processor mode). There is a a hardware register called the Stack Pointer that identifies the current position of the stack. Usually the SP starts at the high end of the stack and works downward. To allocate memory on the stack, the program subtracts the number of bytes required from the stack pointer. To deallocate, it adds to the stack pointer. The allocations and deallocations always take place at the same end.
There are then two operations on the stack. PUSH means put something on the stack. POP removes it. Most processors have instructions to PUSH and POP
If you have
char something
defined within a function, that memory is allocated by the program as directed by the compiler by doing something like this to adjust the stack pointer (I'm leaving out a frame pointer for now)
SUB BYTESNEEDED, SP
upon entering the function and freed by doing
ADD BYTESNEEDED, SP
before leaving the function. During the execution of the function, the local variables are at offsets from the stack pointer.
This usually done by using a second register, usually called a frame pointer. A function usually does something like this at the start
PUSH FP ; Save the old Frame Point
MOV SP FP ; Save the stack pointer
SUB BYTESNEEDED, SP
at the end the function does something like
MOV FP, SP ; Free all the stack allocated by the function
POP FP ; Restore the old stack pointer
The reason for using two registers is that it is possible to dynamically allocate data from the stack.
THere is a common function (although I believe it is not a standard C function) called alloca that is an alternative to malloc that allocates from the stack
void dosomething (int amount)
{
char *data = alloca (amount) ;
}
With alloca, the data is automatically freed when the function returns and resets the stack.
That is a long winded answer to your question. Yes, when declare a char, there has to be an allocation for it. However, this allocation is done behind the scenes without effort on your part.

Why do I have to call CFRelease after __bridge_transfer?

CFArrayRef refAllPeople = ABAddressBookCopyArrayOfAllPeople( addressBook );
NSArray * arPeople = (__bridge_transfer NSArray*)(refAllPeople);
When I analyze it says potential memory leak.
Let me try to understand. refAllPeople have 1 ref count.
Then I do _bridge_transfer. That moves ownership to me. To be more exact, it has arPeople pointing to it and add the retain count by 1. Then the retain count is reduced by one because _bridge_transfer is equivalent with (__bridge) followed by CFRelease.
So,
Why the memory leak complaint?
Your understanding is correct. __bridge_transfer will take refAllPeople back to the world of NSObject where ARC operates and you don't have to explicitly call CFRelease.
I believe it's a static analyser mistake.
From the docs (thanks Carl)
(__bridge_transfer T) op casts the operand, which must have non-retainable pointer type, to the destination type, which must be a retainable object pointer type. ARC will release the value at the end of the enclosing full-expression, subject to the usual optimizations on local values.
It's embarrassing. There is no memory leak :). Somehow I misread the error message and think all blue things means memory leak.
I am glad that my understanding of bridge_transfer is correct and I hope it's useful for everyone.
+1 for others that have answered this :)

How to release a struct that was passed by reference to c code and its member was malloc'ed there?

I'm getting "malloc: * error for object 0xbfffe160: pointer being freed was not allocated" when trying to free memory (in objective-c code) of an object that was allocated inside c function. This C function creates and returns binary data packet that is used as NSData later. Here's my obj-c code part where I'm creating struct variable and passing it by reference to C function:
MyPacket packetRef;
allocAuthentificationCodePacket(&packetRef);
NSData *data = [NSData dataWithBytes:packetRef.bytes length:packetRef.packet->packetSize];
free(&packetRef); // getting error
Everything work fine, except I'm trying to release the memory because the data should be retained by NSData variable. The C functions performs calloc inside itself, so I should somehow to release that memory:
packetRef->bytes = calloc(1, sizeof(*packetRef));
Here's are my structs for storing binary data:
typedef struct {
uint8_t packetType;
uint16_t packetBody;
} MyStruct;
and another struct:
typedef union {
const uint8_t *bytes;
MyStruct *packet;
} MyPacket;
How should I free the memory? The error I'm getting is not crash, it just a message in debug console when running unit tests.
UPDATE. Tried to release "bytes" struct member but getting the same error message:
free(&packetRef.bytes);
UPDATE2. Thanks, the suggested way did worked and malloc error message disappeared from console:
free(packetRef.bytes);
However, getting a warning in Xcode "Passing 'const uint8_t *' (aka 'const unsigned char *') to parameter of type 'void *' discards qualifiers". I'm using Apple LLVM 4.1 compiler. C function resides in separate file and only a header is included because Android guys will have to reuse it.
UPDATE3. Thanks to #simonc and #nos who have pointed out the struct member "bytes" has const. The warning has disappeared after removing const. The initial idea of using const was to protect "bytes" from modification.
This is always wrong. (Hint: It's almost always wrong to put & inside of free().)
MyPacket packetRef;
...
free(&packetRef); // getting error
It doesn't matter what MyPacket is -- it has automatic storage duration, i.e., the compiler automatically allocates storage and frees it when the function exits.
Do not free() something unless it came from malloc() (or calloc(), etc.)
Since packetRef.bytes was allocated with calloc(), you can free() that instead.
MyPacket packetRef;
allocAuthentificationCodePacket(&packetRef);
...
free(packetRef.bytes);
Update
If the function that you call, allocAuthentificationCodePacket, contains the code:
packetRef->bytes = calloc(1, sizeof(*packetRef));
And if the bytes field has type const uint8_t *, then something is wrong.
Perhaps your code is wrong, and you are supposed to call some function to free the packet rather than freeing it yourself.
Perhaps the type of the bytes field is wrong, and should be uint8_t * instead of const uint8_t *.
Perhaps allocAuthentificationCodePacket is wrong.
Who knows? It's not wrong enough to crash, but it is a problem.
Footnote
There are no references in C. &x is "address of x", not "reference to x".
Let's consider the following code:
char *x = malloc(10);
free(x);
When people talk about this code, they will say something like "x is allocated on the heap", but that's not technically correct, x is allocated on the stack and contains the address of 10 bytes on the heap. Likewise, the line free(x) does not actually free x, it frees the memory which x points to.
So when someone tells you, "don't forget to free x", you know they actually mean "don't forget to free the memory which the value contained in x points to". People are sloppy with terminology but computers aren't.
packetRef is a stack variable in your example with packetRef->bytes heap allocated. You should therefore call free(packetRef.bytes)
Since you allocate the memory inside a function - allocAuthentificationCodePacket - you may want to create another function to free the memory
void freePacket(MyPacket* packet)
{
free(packet->bytes);
}

Aren't objective-c pointers nil until when you allocate the memory?

I thought that when I declare an object the pointer is still nil until when I allocate memory and initialize it. Instead I run this code and I was surprised to see that it outputs "TRUE":
NSString * aString;
if (aString) {
NSLog(#"TRUE");
}
thanks
It is pointing at an undefined location - it can point to any memory location (even one that you don't have access to.
You should NIL it out when declaring it.
When you allocate an OBJECT the storage is nilled, but when you have an automatic variable it's whatever junk it is.

iPhone, Object allocated and stored into 'glossPath' is not referenced later (object leaked)

I have this warning in analyzer and also in leaks instrument, how can I fix this leak?
Object allocated on line 86 and stored into 'glossPath' is not referenced later in this execution path and has a retain count of +1 (object leaked)
Tnx
You are responsible for releasing the object returned by CGPathCreateMutable() as per "The Create Rule". It is also stated in the reference:
Return Value
A new mutable path. You are responsible for releasing this object.
You can use CGPathRelease() to release the path.
CGPathRelease(glossPath);