带有struct array字段的sprintf - 获取分段错误

时间:2017-01-28 12:54:00

标签: c

这个想法是格式化模块中的结构的文本信息消息。 当尝试使用(cf module.c)定义消息时,它就像一个魅力:

/*this works*/
module_text3.info_text[0] = "toto[0]";
module_text3.info_text[1] = "toto[1]";

但是当使用sprintf时,我遇到了分段错误(cf module.c):

/*this gives segmentation fault*/
for(cpt=0; cpt < 2; cpt++)
{
  sprintf(module_text3.info_text[cpt], "info[%u]", cpt);
}

3个不同的文件:main.c,module.h和module.c

/*main.c*/
/*gcc -o test main.c module.c*/
#include <stdio.h>
#include "module.h"

int main(int argc, char **argv)
{
  int i;
  struct message3 *ptext3 = moduleFcn3();

  for (i= 0; i < ptext3->info_nb; i++)
  {
    printf("ptext3->info_text[%u]: %s\n", i, ptext3->info_text[i]);
  }
  printf("ptext3->error_text: %s\n", ptext3->error_text);
  printf("ptext3->id: %u\n", ptext3->id);
  printf("ptext3->info_nb: %u\n", ptext3->info_nb);
  printf("ptext3->info_nb_max: %u\n", ptext3->info_nb_max);

  return 0;
}
/*------------------------------------------------------*/
/*module.h*/

#define NB_LINE_MAX 10
struct message3
{
  char *info_text[NB_LINE_MAX]; /*a few info lines.*/
  char *error_text; /*only one line for error.*/
  int id;
  int info_nb_max;
  int info_nb;
};

extern struct message3* moduleFcn3(void);

/*------------------------------------------------------*/
/*module.c*/
#include <stdio.h>
#include "module.h"

/*static is in "Stack".*/
static struct message3 module_text3;

struct message3* moduleFcn3(void)
{
  int cpt = 0;
  struct message3 *ptext;

  /*this gives segmentation fault*/
  for(cpt=0; cpt < 2; cpt++)
  {
    sprintf(module_text3.info_text[cpt], "info[%u]", cpt);
  }

  /*this works*/
//  module_text3.info_text[0] = "toto[0]";
//  module_text3.info_text[1] = "toto[1]";
//  cpt = 2;

  module_text3.error_text = "This is error";
  module_text3.id = 4;
  module_text3.info_nb_max = NB_LINE_MAX;
  module_text3.info_nb = cpt;

  ptext = &module_text3;

  return ptext;
}

我很感激有关如何格式化我的信息消息的任何建议(我们不使用sprintf)。 谢谢,

2 个答案:

答案 0 :(得分:0)

您没有为info_text字符串分配任何内存。你必须首先使用asprintf(),或者如果你的C库支持它(GNU那个),使用sprintf()而不是for(cpt = 0; cpt < 2; cpt++) asprintf(&module_text3.info[cpt], "info[%u]", cpt); 让它分配足够的内存来保存整个输出你的字符串:

module_text3.info_text[0] = "toto[0]";

不要忘记你还必须在某个时候再次释放记忆。

以下行的原因:

"toto[0]"

编译器是否确保字符串module_text3.info_text[0]存储在某处的内存中,您只需将指针{{1}}指向该字符串即可。

答案 1 :(得分:0)

您尚未为info_text字段中的字符串分配空间。最简单的方法是更改​​struct

/*module.h*/

#define NB_LINE_MAX 10
#define INFO_MAX 25

struct message3
{
  char info_text[NB_LINE_MAX][INFO_MAX]; /*a few info lines.*/
  char *error_text; /*only one line for error.*/
  int id;
  int info_nb_max;
  int info_nb;
};

extern struct message3* moduleFcn3(void);
相关问题