简体   繁体   English

堆内存和 malloc 查询

[英]Heap Memory and malloc query

I am trying to get my head around dynamic memory allocation and was hoping someone could explain why the following code executes as it does.我试图了解动态内存分配,并希望有人能解释为什么下面的代码会这样执行。

#include <stdlib.h>
#include <string.h>

char* create_string(void);

int main(){

    char* str1 = NULL;
    char* str2 = NULL;

    str1 = create_string();
    
    str2 = (char*)malloc(11);
    
    str2 = create_string();

    printf("String 1 is: %s", str1);
    
    printf("String 2 is: %s", str2);

    free(str1);

}

char* create_string()
{
    char* stack_str = "TestString";
    char* heap_str = (char*)malloc(strlen(stack_str) + 1);
    strcpy(heap_str, stack_str);
    if(heap_str == NULL)
    {
        printf("Oh no");
        return NULL;
    }

    return heap_str;

}

As far as I thought, to allocate memory on the heap, you have to use malloc with a size which allocates a block of memory and then use a function such as strcpy() or memcpy(), as I have done with str2 above (malloc 11 for the size of "TestString" plus one for the null terminator.)据我所知,要在堆上分配内存,您必须使用具有分配内存块大小的 malloc,然后使用诸如 strcpy() 或 memcpy() 之类的函数,就像我在上面使用 str2 所做的那样( malloc 11 表示“TestString”的大小加上 1 表示空终止符。)

I am just confused why assigning the result of create_string to str1 which is a null pointer which has not been allocated a block of memory produces the same output as str2.我只是很困惑为什么将 create_string 的结果分配给 str1,它是一个尚未分配内存块的空指针会产生与 str2 相同的输出。

Many thanks in advance!提前谢谢了!

"As far as I thought, to allocate memory on the heap, you have to use malloc with a size which..." size in malloc() is number of bytes which is unsigned integer. “据我所知,要在堆上分配内存,您必须使用 malloc 的大小……” malloc() 中的大小是无符号整数的字节数。 Therefore syntactically str2 = (char*)malloc(11);因此在语法上str2 = (char*)malloc(11); is correct.是正确的。

Both str1 and str2 are pointing to different memory locations from the heap containing "TestString". str1 和 str2 都指向包含“TestString”的堆中不同的内存位置。 This is according to what you have programmed.这是根据您编程的内容。 However str2 = (char*)malloc(11);然而str2 = (char*)malloc(11); returns 11 bytes of memory that can store character data type and returns a pointer to this location in heap.返回可存储字符数据类型的 11 字节内存,并返回指向堆中该位置的指针。 There is no issue in this.这没有问题。 However, in your code you have leaked this allocation when you assign create_string() pointer to it.但是,在您的代码中,当您将 create_string() 指针分配给它时,您已经泄漏了此分配。

It is not wroking exactly as you think.它并不像你想象的那样工作。

Firstly, C has constant strings, which will be initialized by double quotes.首先,C 有常量字符串,它会被双引号初始化。 Those objects when used, actually return a pointer that points to the location of the initialized constant string array.这些对象在使用时,实际上返回一个指向初始化常量字符串数组位置的指针。

char * ptr="something"   //"something" return a pointer to the location of the string array 
                         // and is assigned to the ptr.

You don't need to allocate memory for constant string as they are managed by compilers.您不需要为常量字符串分配内存,因为它们由编译器管理。 What's happening in the code is stack_str locates to this constant string array which is managed by the compiler.代码中发生的事情是stack_str定位到这个由编译器管理的常量字符串数组。 So it is always present.所以它一直存在。 You create a memory block and stores the address in heap_str , and copies the stack_str contents to the dynamically allocated memory, and returns the pointer.您创建一个内存块并将地址存储在heap_str ,并将stack_str内容复制到动态分配的内存中,并返回指针。 In effect,有效,

 str2 = (char*)malloc(11);

is not used for anything and is wasted.不用于任何东西并且被浪费了。 Hope you understands.希望你明白。

Edit: In your create_str() , you check heap_str isn't NULL AFTER strcpy() .编辑:在你的create_str() ,你检查heap_strstrcpy()之后不是 NULL 。 If the malloc() failed for some reason, the program will still crash even if you check for NULL.如果malloc()由于某种原因失败,即使您检查 NULL 程序仍然会崩溃。

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

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