有没有办法(在纯C中)区分malloc
ed字符串和字符串文字,而不知道哪个是哪个?严格地说,我正试图找到一种方法来检查变量是否是一个malloced字符串,如果是,我会释放它; 如果没有,我会放手.
当然,我可以向后挖掘代码并确保变量是否被malloc
编辑,但以防万一存在简单方法...
编辑:添加行以使问题更具体.
char *s1 = "1234567890"; // string literal
char *s2 = strdup("1234567890"); // malloced string
char *s3;
...
if (someVar > someVal) {
s3 = s1;
} else {
s3 = s2;
}
// ...
// after many, many lines of code an algorithmic branches...
// now I lost track of s3: is it assigned to s1 or s2?
// if it was assigned to s2, it needs to be freed;
// if …
Run Code Online (Sandbox Code Playgroud) 这是我的代码:
typedef struct bobTheBuilder{
char *name;
int fix;
int max;
};
int main(void){
struct bobTheBuilder bob;
initBob(&bob);
del(&bob);
system("PAUSE");
return (0);
}
void initBob(struct bobTheBuilder *currBob)
{
char *n="bob";
currBob->name = (char*)malloc(sizeof(char)*strlen(n));
strcpy((*currBob).name, n);
(*currBob).fix = 0;
(*currBob).max = 3;
}
void del(struct bobTheBuilder *currBob)
{
free(currBob->name);
}
Run Code Online (Sandbox Code Playgroud)
视觉工作室打断了free
句子.
我该怎么办?是问题free
还是malloc
?