我正在看下面的程序,不知道如何分配内存,为什么:
void function() { char text1[] = "SomeText"; char* text2 = "Some Text"; char *text = (char*) malloc(strlen("Some Text") + 1 ); }
在上面的代码中,最后一个代码显然是在堆中.但是,据了解,text2在程序的数据段中,而text1可能位于堆栈中.还是我的假设错了?这里有什么正确的假设?这个编译器是否依赖?
谢谢
解决方法
// Array allocated on the stack and initialized with "SomeText" string. // It has automatic storage duration. You shouldn't care about freeing memory. char text1[] = "SomeText"; // Pointer to the constant string "Some Text". // It has static storage duration. You shouldn't care about freeing memory. // Note that it should be "a pointer to const". // In this case you'll be protected from accidential changing of // the constant data (changing constant object leads to UB). const char* text2 = "Some Text"; // malloc will allocate memory on the heap. // It has dynamic storage duration. // You should call "free" in the end to avoid memory leak. char *text = (char*) malloc(strlen("Some Text") + 1 );