相关疑难解决方法(0)

296
推荐指数
6
解决办法
38万
查看次数

如何区分malloced字符串和字符串文字?

有没有办法(在纯C中)区分malloced字符串和字符串文字,而不知道哪个是哪个?严格地说,我正试图找到一种方法来检查变量是否是一个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)

c string malloc char

8
推荐指数
1
解决办法
191
查看次数

如何在struct中释放指针?

这是我的代码:

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

c struct pointers

1
推荐指数
1
解决办法
239
查看次数

标签 统计

c ×3

char ×1

function ×1

malloc ×1

pointers ×1

strdup ×1

string ×1

struct ×1