如何区分动态分配的 char* 和静态 char*

How to tell difference between dynamically allocated char* and static char*

在我正在处理的程序中,我有一个类似于

的结构
typedef struct _mystruct{
    char* my_string;
} mystruct;

大部分时间my_string是使用malloc分配的,所以有一个函数调用

free(mystructa->my_string);  

通常这可行,但在某些时候,my_string 被设置为文字

my_string = "This is a literal"; 

有没有办法在调用 free() 之前区分两者?

无法可靠地区分指向文字的指针和指向已分配内存的指针。您将不得不推出自己的解决方案。有两种方法可以解决这个问题:

1) 在struct中设置一个标志,指示是否应释放指针。

typedef struct _mystruct {
    char *my_string;
    int string_was_allocated;
} mystruct;

mystructa.my_string = malloc(count);
mystructa.string_was_allocated = 1;
.
.
if (mystructa.string_was_allocated)
   free(mystructa.my_string);

mystructa.my_string = "This is a literal";
mystructa.string_was_allocated = 0;

2) 始终使用 strdup.

动态分配
mystructa.my_string = strdup("This is a literal");
free(mystructa.my_string);

这两种方法都涉及对现有代码的更改,但我认为解决方案 2 更加健壮、可靠和可维护。

动态内存和静态内存分到不同的地方:栈和堆

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

int main(int argc, char* argv[]) {

char aString[] = "this is a string";

printf("the string is located at %x \n", &aString);


char * pString = (char*) malloc(sizeof(char) * 64);
strcpy(pString, "this is a dynamic string");

printf("the pointer is located at %x \n", &pString);

printf("the dynamic string is located at %x \n\n", &*pString);



return 0;
}

/************* *** **************/

robert@debian:/tmp$ gcc test.c 
robert@debian:/tmp$ ./a.out
the string is located at bfcdbe8f 
the pointer is located at bfcdbe88 
the dynamic string is located at 95a3008