C language learning: malloc () function

Function declaration:

void *malloc(size_t size)

head File:

#include <stdio.h>

Function Description:

  • Allocating memory space required, and returns a pointer to it.

parameter:

  • size - the size of the memory block, in bytes.

return value:

  • The function returns a pointer to the allocated memory size. If the request fails, NULL is returned.

Example:

The following example demonstrates the malloc () function usage.

#include <stdio.h>
#include <stdlib.h>

void update_value(int* p){
	*p = 100;
}

int main()
{
	//在栈上面分配变量a 占4个字节
	int a = 10;
   	//申请类型是int内存空间;占4个字节;p指针指向该4个字节的内存空间        
   	int *p = (int*)malloc(sizeof(int));
   	//p变量也占4字节;所以sizeof(p)=8个字节
   	//赋值p只指向的动态空间为50
   	*p = 50;
   	printf("p->value=%d &p=%p sizeof(*p)=%ld, sizeof(p)=%ld sizeof(a)=%ld \n", *p, p, sizeof(*p), sizeof(p),sizeof(a));

   	free(p);//修改p指向的内存中的数据
   	printf("p->value=%d &p=%p sizeof(*p)=%ld, sizeof(p)=%ld sizeof(a)=%ld \n", *p, p, sizeof(*p), sizeof(p),sizeof(a));
 
 	update_value(p);
 	printf("p->value=%d &p=%p sizeof(*p)=%ld, sizeof(p)=%ld sizeof(a)=%ld \n", *p, p, sizeof(*p), sizeof(p),sizeof(a));
   	return(0);
}

NOTE: When unused memory, use the free () function of the memory blocks freed.

void *: undetermined type represents a pointer, C / C ++ provisions void*can be converted to any other type of strong hands, there is a saying that is void on any other type can be assigned to it directly, without the need for strong turn, but not vice versa can.

the malloc : allocated memory size is at least the number of bytes specified by the parameters.

mallocThe return value is a pointer to the starting location in memory available period, the available period of the start point address of the memory, multiple calls to mallocthe assigned address not overlap unless malloc assigned a particular address should be released out malloc It should be completed as soon as possible and return to memory allocation (allocation algorithm can not use the memory of the NP-hard) malloc achieved while achieving release of memory and memory size adjusting function (realloc and free)

mallocAnd freeare paired, does not release memory leak if the application is, if for no reason and that is the release did not do anything, can only be released once released, if a space to release two or more times incorrectly (but released null pointer exception occurs, the release of a null pointer is also equal to nothing to do, so how many times the release is possible.)

Published 100 original articles · won praise 45 · views 640 000 +

Guess you like

Origin blog.csdn.net/wangzhongshun/article/details/101430545