All Questions

1883
votes
27answers
154517 views

Do I cast the result of malloc?

In this question, someone suggested in a comment that I should not cast the result of malloc, i.e. int *sieve = malloc(sizeof(int) * length); rather than: int *sieve = (int *) malloc(sizeof(int) *...
98
votes
11answers
236664 views

How do you allow spaces to be entered using scanf?

Using the following code: char *name = malloc(sizeof(char) + 256); printf("What is your name? "); scanf("%s", name); printf("Hello %s. Nice to meet you.\n", name); A user can enter their name bu...
23
votes
4answers
4316 views

How do I correctly set up, access, and free a multidimensional array in C?

I have seen dozens of questions about “what’s wrong with my code” regarding multidimensional arrays in C. For some reason people can’t seem to wrap their head around what is happening here, so...
224
votes
15answers
111002 views

How do malloc() and free() work?

I want to know how malloc and free work. int main() { unsigned char *p = (unsigned char*)malloc(4*sizeof(unsigned char)); memset(p,0,4); strcpy((char*)p,"abcdabcd"); // **deliberately st...
337
votes
18answers
194962 views

In what cases do I use malloc vs new?

I see in C++ there are multiple ways to allocate and free data and I understand that when you call malloc you should call free and when you use the new operator you should pair with delete and it is a...
205
votes
3answers
37853 views

Why malloc+memset is slower than calloc?

It's known that calloc is different than malloc in that it initializes the memory allocated. With calloc, the memory is set to zero. With malloc, the memory is not cleared. So in everyday work, I reg...
309
votes
23answers
92296 views

Why is the use of alloca() not considered good practice?

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 dynamicall...
582
votes
17answers
401326 views

Difference between malloc and calloc?

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 o...
389
votes
16answers
78446 views

What REALLY happens when you don't free after malloc?

This has been something that has bothered me for ages now. We are all taught in school (at least, I was) that you MUST free every pointer that is allocated. I'm a bit curious, though, about the real...
45
votes
8answers
63499 views

C Programming: malloc() inside another function

I need help with malloc() inside another function. I'm passing a pointer and size to the function from my main() and I would like to allocate memory for that pointer dynamically using malloc() from i...

Previous Next