malloc(sizeof(int)) vs malloc(sizeof(int *)) vs (int *)malloc(sizeof(int))

malloc(sizeof(int)) means you are allocating space off the heap to store an int. You are reserving as many bytes as an int requires. This returns a value you should cast to int *. (A pointer to an int.) As some have noted, typical practice in C is to let implicit casting take care of this. malloc(sizeof(int*)) means you are allocating space off the heap … Read more

How to allocate array of pointers for strings by malloc in C?

As I can understand from your assignment statement in while loop I think you need array of strings instead: Note: By doing = in while loop as below: you are just assigning address of string (its not deep copy), but because you are also writing “only address of strings” so I think this is what you wants. … Read more

Casting a pointer to an int

I am writing my own functions for malloc and free in C for an assignment. I need to take advantage of the C sbrk() wrapper function. From what I understand sbrk() increments the program’s data space by the number of bytes passed as an argument and points to the location of the program break. If … Read more

Allocating char array using malloc

Yes, it’s a matter of style, because you’d expect sizeof(char) to always be one. On the other hand, it’s very much an idiom to use sizeof(foo) when doing a malloc, and most importantly it makes the code self documenting. Also better for maintenance, perhaps. If you were switching from char to wchar, you’d switch to … Read more

Difference between sizeof(char) and sizeof(char *)

char is a character and sizeof(char) is defined to be 1. (N1570 6.5.3.4 The sizeof and _Alignof operators, paragraph 4) char* is a pointer to a character and sizeof(char*) depends on the environment. It is typically 4 in 32-bit environment and 8 in 64-bit environment. In typical environment where sizeof(char*) > sizeof(char), malloc(sizeof(char*)*len + 1) will (at least try to) allocate more memory than malloc(sizeof(char)*len + 1) if len is small … Read more

Incorrect checksum for freed object on malloc

In read_response, you are probably overwriting the end of the buffer pointed to by buf. The problem is that buf is a pointer, so sizeof(buf) will return the size of a pointer (probably 4 or 8 depending on your CPU). You are using sizeof as if buf were an array, which is not really the same thing as a pointer in C although … Read more

Allocating string with malloc

malloc() returns a void* pointer to a block of memory stored in the heap. Allocating with malloc() does not initialize any string, only space waiting to be occupied.To add a null-terminating character, you either have to do this yourself, or use a function like scanf(), which adds this character for you. Having said this, you … Read more