malloc interview questions
Top malloc frequently asked interview questions
In this question, someone suggested in a comment that I should not cast the results of malloc
, i.e:
int *sieve = malloc(sizeof(int)*length);
rather than:
int *sieve = (int *)malloc(sizeof(int)*length);
Why would this be the case?
Source: (StackOverflow)
What is the difference between doing:
ptr = (char **) malloc (MAXELEMS * sizeof(char *));
or:
ptr = (char **) calloc (MAXELEMS, sizeof(char*));
When is it a good idea to use calloc over malloc or vice versa?
Source: (StackOverflow)
alloca()
allocates memory from Stack rather than heap which is case in malloc()
. So, when I return from the routine the memory is freed. So, actually this solves my problem of freeing up of dynamically allocated memory. Freeing of memory allocated through malloc()
is a major headache and if somehow missed leads to all sorts memory problems.
Why is the use of alloca()
discouraged in spite of the above features?
Source: (StackOverflow)
If I use malloc
in my code:
int *x = malloc(sizeof(int));
I get this warning from gcc
:
new.c:7: warning: implicit declaration of function ‘malloc’
new.c:7: warning: incompatible implicit declaration of built-in function ‘malloc’
I'm new to C. Am I doing something wrong?
Source: (StackOverflow)
I have the following C
code :
int *a;
size_t size = 2000*sizeof(int);
a = (int *) malloc(size);
which works fine. But if I have the following :
char **b = malloc(2000*sizeof *b);
where every element of b
has different length.
How is it possible to do the same thing for b
as i did for a
; i.e. the following code would hold correct?
char *c;
size_t size = 2000*sizeof(char *);
c = (char *) malloc(size);
Source: (StackOverflow)
I'm programming an application in Objective-C and I'm getting this error:
MyApp(2121,0xb0185000) malloc: *** error for object 0x1068310: double free
*** set a breakpoint in malloc_error_break to debug
It is happening when I release an NSAutoreleasePool and I can't figure out what object I'm releasing twice.
How do I set his breakpoint?
Is there a way to know what is this "object 0x1068310"?
thanks in advance
Gonso
Source: (StackOverflow)
This question already has an answer here:
What does malloc(0)
returns? Would the answer be same for realloc(malloc(0),0)
?
#include<stdio.h>
#include<malloc.h>
int main()
{
printf("%p\n", malloc(0));
printf("%p\n", realloc(malloc(0), 0));
return 0;
}
Output from linux gcc:
manav@manav-workstation:~$ gcc -Wall mal.c
manav@manav-workstation:~$ ./a.out
0x9363008
(nil)
manav@manav-workstation:~$
The output keep changing everytime for malloc(0)
. Is this a standard answer? And why would anyone be interested in getting such a pointer, other than academic research?
EDIT:
If malloc(0)
returns dummy pointer, then how does following works:
int main()
{
void *ptr = malloc(0);
printf("%p\n", realloc(ptr, 1024));
return 0;
}
EDIT:
The following code outputs "possible" for every iteration. Why should it not fail ?
#include<stdio.h>
#include<malloc.h>
int main()
{
int i;
void *ptr;
printf("Testing using BRUTE FORCE\n");
for (i=0; i<65000; i++)
{
ptr = malloc(0);
if (ptr == realloc(ptr, 1024))
printf("Iteration %d: possible\n", i);
else
{
printf("Failed for iteration %d\n", i);
break;
}
}
return 0;
}
Source: (StackOverflow)
What is the proper/preferred way to allocate memory in a C API?
I can see, at first, two options:
1) Let the caller do all the (outer) memory handling:
myStruct *s = malloc(sizeof(s));
myStruct_init(s);
myStruct_foo(s);
myStruct_destroy(s);
free(s);
The _init
and _destroy
functions are necessary since some more memory may be allocated inside, and it must be handled somewhere.
This has the disadvantage of being longer, but also the malloc can be eliminated in some cases (e.g., it can be passed a stack-allocated struct:
int bar() {
myStruct s;
myStruct_init(&s);
myStruct_foo(&s);
myStruct_destroy(&s);
}
Also, it's necessary for the caller to know the size of the struct.
2) Hide malloc
s in _init
and free
s in _destroy
.
Advantages: shorter code, since the functions are going to be called anyway. Completely opaque structures.
Disadvantages: Can't be passed a struct allocated in a different way.
myStruct *s = myStruct_init();
myStruct_foo(s);
myStruct_destroy(foo);
I'm currently leaning for the first case; then again, I don't know about C API design.
Source: (StackOverflow)
I enabled memory checking in Xcode (Edit Scheme -> Options). I'm now getting the following when I perform on device debugging: dyld: could not load inserted library '/usr/lib/libgmalloc.dylib' because image not found
. The measure was taken proactively in hopes of catching mistakes early in the cycle.
Is memory checking not valid on a device? It appears its valid since it was acknowledged and investigated according to http://lists.apple.com/archives/xcode-users/2012/Mar/msg00271.html. Also, Xcode had no complaints during compile and link. If its not valid for a device, why is Xcode inserting the library? Are there any solutions? Googling returned a few hits, but I did not see any concrete solutions.
How does one enable Xcode Guard Malloc when debugging on a device?
Source: (StackOverflow)
On Linux if I were to malloc(1024 * 1024 * 1024)
, what does malloc actually do?
I'm sure it assigns a virtual address to the allocation (by walking the free list and creating a new mapping if necessary), but does it actually create 1 GiB worth of swap pages? Or does it mprotect
the address range and create the pages when you actually touch them like mmap
does?
(I'm specifying Linux because the standard is silent on these kinds of details, but I'd be interested to know what other platforms do as well.)
Source: (StackOverflow)
if I allocate some memory using malloc()
is there a way to mark it readonly. So memcpy() fails if someone attempt to write to it?
This is connected to a faulty api design where users are miss-using a const pointer returned by a method GetValue()
which is part of large memory structure. Since we want to avoid copying of large chunk of memory we return live pointer within a structured memory which is of a specific format. Now problem is that some user find hack to get there stuff working by writing to this memory directly and avoid SetValue() call that does allocation and properly handing in memory binary format that we have developed. Although there hack sometime work but sometime it causes memory access violation due to incorrect interpretation of control flags which has been overridden by user.
Educating user is one task but let say for now we want there code to fail.
I am just wondering if we can simply protect against this case.
For analogy assume someone get a blob column from sqlite statement and then write back to it. Although in case of sqlite it will not make sense but this somewhat happing in our case.
Source: (StackOverflow)
I'm trying to learn C and I'm currently trying to write a basic stack data structure, but I can't seem to get basic malloc
/free
right.
Here's the code I've been using (I'm just posting a small part here to illustrate a specific problem, not the total code, but the error message was generated just by running this example code in valgrind
)
#include <stdio.h>
#include <stdlib.h>
typedef struct Entry {
struct Entry *previous;
int value;
} Entry;
void destroyEntry(Entry entry);
int main(int argc, char *argv[])
{
Entry* apple;
apple = malloc(sizeof(Entry));
destroyEntry(*(apple));
return 0;
}
void destroyEntry(Entry entry)
{
Entry *entry_ptr = &entry;
free(entry_ptr);
return;
}
When I run it through valgrind
with --leak-check=full --track-origins=yes
, I get the following error:
==20674== Invalid free() / delete / delete[] / realloc()
==20674== at 0x4028E58: free (vg_replace_malloc.c:427)
==20674== by 0x80485B2: destroyEntry (testing.c:53)
==20674== by 0x8048477: main (testing.c:26)
==20674== Address 0xbecc0070 is on thread 1's stack
I think this error means that the destroyEntry
function is not allowed to modify memory allocated explicitly in main. Is that right? Why can't I just free
the memory I allocated in main
in another function? (and is this behavior somehow specific to main?)
Source: (StackOverflow)
Surprisingly simple/stupid/basic question, but I have no idea: Suppose I want to return the user of my function a C-string, whose length I do not know at the beginning of the function. I can place only an upper bound on the length at the outset, and, depending on processing, the size may shrink.
The question is, is there anything wrong with allocating enough heap space (the upper bound) and then terminating the string well short of that during processing? i.e. If I stick a '\0' into the middle of the allocated memory, does (a.) free()
still work properly, and (b.) does the space after the '\0' become inconsequential? Once '\0' is added, does the memory just get returned, or is it sitting there hogging space until free()
is called? Is it generally bad programming style to leave this hanging space there, in order to save some upfront programming time computing the necessary space before calling malloc?
To give this some context, let's say I want to remove consecutive duplicates, like this:
input "Hello oOOOo !!" --> output "Helo oOo !"
... and some code below showing how I'm pre-computing the size resulting from my operation, effectively performing processing twice to get the heap size right.
char* RemoveChains(const char* str)
{
if (str == NULL) {
return NULL;
}
if (strlen(str) == 0) {
char* outstr = (char*)malloc(1);
*outstr = '\0';
return outstr;
}
const char* original = str; // for reuse
char prev = *str++; // [prev][str][str+1]...
unsigned int outlen = 1; // first char auto-counted
// Determine length necessary by mimicking processing
while (*str) {
if (*str != prev) { // new char encountered
++outlen;
prev = *str; // restart chain
}
++str; // step pointer along input
}
// Declare new string to be perfect size
char* outstr = (char*)malloc(outlen + 1);
outstr[outlen] = '\0';
outstr[0] = original[0];
outlen = 1;
// Construct output
prev = *original++;
while (*original) {
if (*original != prev) {
outstr[outlen++] = *original;
prev = *original;
}
++original;
}
return outstr;
}
Source: (StackOverflow)