简体   繁体   English

C中的动态内存分配

[英]Dynamic memory allocation in C

i just experiment the things on the c language could you answer my question regarding the program i've written 我只是用C语言进行实验,您能否回答有关我编写的程序的问题

void main()
{
    char *p,; // created a  pointer pointing to string
    p = (char *) malloc(50); // dynamically create 50 bytes.
    strcpy(p, "this code is written about the dynamic allocation");
    p += 20;
    free(p);
}

Now could anyone tell me what is the effect of free(p) statement will the last 30 bytes will be freed of and used for the future memory allocation.? 现在谁能告诉我free(p)语句的作用是什么,最后30个字节将被释放并用于将来的内存分配? what would be the output? 输出是什么?

You are not supposed to free any addresses but those returned by malloc() , calloc() or realloc() . 您不应该释放任何地址,而是释放malloc()calloc()realloc()返回的地址。 And p + 20 is no such address. p + 20不是这样的地址。 http://codepad.org/FMr3dvnq shows you that such a free() is likely to fail. http://codepad.org/FMr3dvnq向您显示了这样的free()可能会失败。

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc() . free()函数释放ptr指向的内存空间,该内存空间必须已由先前对malloc(),calloc()或realloc()的调用返回 Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. 否则,或者如果之前已经调用过free(ptr),则会发生未定义的行为 If ptr is NULL, no operation is performed. 如果ptr为NULL,则不执行任何操作。

Does the pointer passed to free() have to point to beginning of the memory block, or can it point to the interior? 传递给free()的指针是否必须指向内存块的开始,还是可以指向内部? is also worth reading. 也值得一读。

Even if you could use free() on any pointer that points to a malloc'd memory - your could would free it twice since you are calling free() on more than one memory inside that area. 即使您可以在指向malloc的内存的任何指针上使用free() ,也可以将其释放两次,因为您要在该区域内的多个内存上调用free() And double-frees are evil as they can result in security holes. 而且双重释放是邪恶的,因为它们可能导致安全漏洞。

It will result in Undefined Behavior. 这将导致未定义的行为。

The free() function shall cause the space pointed to by ptr to be deallocated; free()函数应使ptr指向的空间被释放; that is, made available for further allocation. 也就是说,可供进一步分配。 If ptr is a null pointer, no action shall occur. 如果ptr是空指针,则不会发生任何动作。 Otherwise, if the argument does not match a pointer earlier returned by the calloc() , malloc() , posix_memalign() , realloc() , strdup() function, or if the space has been deallocated by a call to free() or realloc() , the behavior is undefined . 否则, 如果参数与calloc()malloc()posix_memalign()realloc()strdup()函数返回的指针不匹配,或者通过调用free()释放了空间,或者realloc() ,行为是不确定的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM