在结构中使用字符串时的分割故障

Segmentation fault when using string in structure

本文关键字:分割 故障 字符串 结构      更新时间:2023-10-16

我数据库中的表有一个blob类型列。我用它来存储以下结构:

struct a
{
int x;
string y;
} ;

我已经写了一个C 功能来使用上述结构的变量来检索此斑点。我正在为此使用cass_value_get_bytes函数。

问题在于,如果使用上述结构,我会遇到细分故障。但是,如果我将字符串类型更改为字符数组,则问题可以解决。我无法理解为什么我不能使用字符串变量,因为它使用字符串比字符数组更加整洁。

功能cass_value_get_string()cass_value_get_bytes()将指针返回到其寿命与CassResult绑定的缓冲区。当结果删除时,值的内存也是如此。您需要将内存复制到字符串的缓冲区中。cass_value_get_string()也可以用于斑点,并且避免必须执行reinterpret_cast<>。您可以做以下操作:

#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