简体   繁体   English

在结构中使用字符串时出现分段错误

[英]Segmentation fault when using string in structure

The table in my database has got one blob type column. 我数据库中的表只有一个Blob类型列。 I use it to store the following structure: 我用它来存储以下结构:

struct a
{
int x;
string y;
} ;

I've written a C++ function to retrieve this blob using the above mentions structure's variable. 我已经编写了一个C ++函数来使用上述结构的变量来检索此blob。 I'm using cass_value_get_bytes function for that. 我为此使用cass_value_get_bytes函数。

The problem is that I get a segmentation fault if I use the above mentioned structure. 问题是,如果使用上述结构,则会出现分段错误。 However if I change the string type to a character array, the problem solves. 但是,如果我将字符串类型更改为字符数组,问题就解决了。 I'm unable to understand why can't I use a string variable as it's so much neater to use a string than a character array. 我不明白为什么我不能使用字符串变量,因为使用字符串比使用字符数组要整齐。

The functions cass_value_get_string() and cass_value_get_bytes() return a pointer into a buffer whose lifetime is bound to CassResult . 函数cass_value_get_string()cass_value_get_bytes()将指针返回到其生存期绑定到CassResult When the result is deleted so is the memory of the values. 删除结果时,值的存储也将删除。 You need to copy the memory into the string's buffer. 您需要将内存复制到字符串的缓冲区中。 cass_value_get_string() can also be used for blobs and it avoid having to do a reinterpret_cast<> . cass_value_get_string()也可用于blob,并且避免了必须执行reinterpret_cast<> You can do something like the following: 您可以执行以下操作:

#include <cassandra.h>
#include <string>

std::string to_string(CassValue* value) {
  const char* str;
  size_t len;
  cass_value_get_string(value, &str, &len);
  return std::string(str, len);
}

struct SomeData {
  int x;
  std::string y;
};

int main() {
  SomeData data;
  CassValue* value = NULL; /* This needs to be set from the result */
  data.y = to_string(value);
}
 You need to allocate memory dynamically,Watch this Example.

 #include<stdlib.h>
 #include<string.h>
 #include<stdio.h>
struct employee{
int no;
char name[20];
double sal;
 } ;




void main()
{

 struct employee emp={
         1234,"Aravind",20000.0
                     };
       struct employee *e=(struct employee*) malloc( sizeof(struct   employee)*1 );


  strcpy(e->name,"Byju");
  e->sal=20000.0;
  e->no=1265;
  printf("\n %d    \t %s \t %lf",emp.no,emp.name,emp.sal);
  printf("\n %d    \t %s \t %lf",e->no,e->name,e->sal);

   }
   Output:
   1234      Aravind     20000.000000
   1265      Byju        20000.000000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM