【问题标题】:is this a segmentation fault? program freezes. (c)这是分段错误吗?程序冻结。 (C)
【发布时间】:2011-11-27 05:09:11
【问题描述】:

当我运行它时,它会打印出正确的东西,但随后会冻结?这是分段错误吗?

int main(int argc, char** argv) {
  int NumElements = 2; /* the number of elements in the string array */
  String* string = (String*) malloc((sizeof (String*)) * NumElements); /* allocate some memory for the app to use */
  unsigned int BytesReserved = ((sizeof (String*)) * NumElements); /* the amount of bytes reserved */

  /* debug */
  printf("Number of elements: %d\nAmount of bytes reserved: %u\n", NumElements, BytesReserved);
  string[0] = String_Set("Hello, ");
  string[1] = String_Set("world!");

  /* loop through the array of strings and print each one */
  int i;
  for (i = 0; i < NumElements; i++) {
    printf("%s\n", String_CString(string[i]));
  }

  free(string); /* deallocate the allocated memory we used earlier */
  return 0;
}

【问题讨论】:

  • 我没有看到任何分段错误...您可以尝试一下吗?注释掉free(string) 部分,然后重试...
  • 如果你在linux上,试试valgrind

标签: c struct segmentation-fault


【解决方案1】:

如果您想要一个首先需要的字符串数组,您似乎为“字符串”分配的空间太少了 分配数组,然后为数组中的每个字符串分配

String** string = malloc((sizeof (String*)) * NumElements);  // notice the extra *

现在对于“字符串”中的每个字符串,您需要分配可以包含您要存储的整个字符串的空间:

string[0] = malloc( strlen( "Hello, " ) + 1 ) // (including trailing \0)
strcpy( string[0], "Hello, " );

不确定你在 String_Set 中做了什么,也许你正在这样做

【讨论】:

  • 谢谢你清理了这么多,String_Set 几乎是 strdup
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
  • 1970-01-01
  • 1970-01-01
  • 2016-12-15
  • 1970-01-01
  • 1970-01-01
  • 2015-06-14
相关资源
最近更新 更多