HOWTO检查,如果一个char *指向一个字符串用C字面 [英] Howto check if a char* points to a string literal in C

查看:162
本文介绍了HOWTO检查,如果一个char *指向一个字符串用C字面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构

struct request {
  int code;
  char *message;
};

这是我想正确的释放。​​

that I'd like to free properly.

我有下面的函数来做到这一点:

I have the following function to do that:

void free_request(struct request *req) {
  if (req->message != NULL) {
      free(req->message);
  }
  free(req);
  req = NULL;
}

问题是,我得到一个自由():无效的指针/段错误错误在编译器中,当我尝试释放已使用一个字符串创建一个请求:

The problem is that I get an "free(): invalid pointer"/segfault error from the compiler when I try to free a request that has been created using a string literal:

struct request *req;
req = malloc(sizeof(struct request));
req->message = "TEST";
free_request(req);

由于我要创建在不同的地方要求结构,用文字一旦(客户端),一旦使用*字符,我从一个套接字读取(在​​服务器端),我想知道是否有做一个函数确保我不尝试释放文字,同时还允许我自由我所创建的消息使用的malloc。

Since I want to create request structs in different places, once using literals (on the client side) and once using *chars that I read from a socket (on the server side) I was wondering if there is a function to make sure that I don't try to free the literals while still allowing me to free the message I have created using a malloc.

推荐答案

有没有让你知道,如果一个指针是动态分配的,或不标准的功能。你应该在你的结构一个标志告知自己的,或者只使用动态分配的字符串(的strdup 是在这种情况下的朋友)。根据您的网络设置,这可能是简单的使用的strdup (嗯,说实话,它的的简单使用的strdup 在所有)。

There is no standard function that lets you know if a pointer was dynamically allocated or not. You should include a flag in your struct to inform yourself of it, or only use dynamically allocated strings (strdup is your friend in this case). Depending on your networking setup, it might be simpler to use strdup (well, to tell the truth, it is simpler to use the strdup at all).

使用的strdup

struct message* req;
req = malloc(sizeof *req);
req->message = strdup("TEST");
free_request(req);

通过一个标志:

struct message
{
    int code;
    char* message;
    bool isStatical; // replace to 'char' if bool doesn't exist
};

void free_request(struct message* req)
{
    if (!req->isStatical) free(req->message);
    free(req);
}

struct message* req;
req = malloc(sizeof *req);
req->message = "TEST";
req->isStatical = 1;
free_request(req);

另外,不要忘了,当你创建一个对象来零时,您分配的内存。这可以为您节省了不少麻烦。

Also, don't forget to zero your allocated memory when you create an object. That could save you a lot of trouble.

req = malloc(sizeof *req);
memset(req, 0, sizeof *req);

这和设置 REQ free_request NULL >将不会有任何效果。您可能需要采取结构信息** 或自己做后的函数调用。

That, and setting req to NULL from free_request won't have any effect. You either need to take a struct message** or do it yourself after the function calls.

这篇关于HOWTO检查,如果一个char *指向一个字符串用C字面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆