calloc

Calloc with structure with pointers in C

邮差的信 提交于 2019-11-26 22:01:23
问题 I know that calloc request memory to be used, writes 0 on all the bits and then returns a pointer to it. My question is: if I use calloc with a structure that contains pointers, will those pointers have the NULL value or do I have to set them to point to NULL? struct a{ char * name; void * p; }* A; So basically, will name and p point to NULL after I've used calloc with struct a? Thanks! 回答1: Somehow you've gotten a lot of incorrect answers. C does not require the representation of null

Proper usage of realloc()

旧街凉风 提交于 2019-11-26 11:26:19
问题 From man realloc:The realloc() function returns a pointer to the newly allocated memory, which is suitably aligned for any kind of variable and may be different from ptr, or NULL if the request fails. So in this code snippet: ptr = (int *) malloc(sizeof(int)); ptr1 = (int *) realloc(ptr, count * sizeof(int)); if(ptr1 == NULL){ //reallocated pointer ptr1 printf(\"Exiting!!\\n\"); free(ptr); exit(0); }else{ free(ptr); //to deallocate the previous memory block pointed by ptr so as not to leave

Difference between malloc and calloc?

泪湿孤枕 提交于 2019-11-25 23:04:11
问题 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? 回答1: calloc() zero-initializes the buffer, while malloc() leaves the memory uninitialized. EDIT: Zeroing out the memory may take a little time, so you probably want to use malloc() if that performance is an issue. If initializing the memory is more important, use calloc() . For example,