【问题标题】:C - segmentation core dump on strcpy()C - strcpy() 上的分段核心转储
【发布时间】:2014-04-30 20:27:26
【问题描述】:

每次尝试运行此函数时都会遇到分段错误。

char *hist_array[20];
int history_counter = 0;

void save_to_history(char *temp){
    temp = malloc(512);/*512 is the size of temp array*/
    printf("temp = %s\narray = %s",temp,hist_array[history_counter]);/*debug*/
    strcpy(hist_array[history_counter],temp);
    printf("Saved %s to history to %d\n\n",hist_array[history_counter],history_counter);
    history_counter++;
}

我不确定我是否正确使用了malloc,但据我了解,它应该有助于将我的字符串temp 正确保存到字符串数组hist_array。此外,temp 永远不会是NULL

编辑 1: 将 sizeof(temp) 更改为正确的大小 512,仍然得到 segfault

【问题讨论】:

  • 不,这行不通。 sizeof(temp) 是指针的大小,而不是传入的字符串。您需要将字符串大小作为参数传入。
  • 您似乎还用指向新的未初始化内存块的指针覆盖了传入的指针 - 然后将其用作 strcpy 的源。
  • @OldProgrammer @Baldrick 我已将 sizeof(temp) 更改为正确的值,但仍然出现段错误。 @Baldrick 所以我需要初始化数组hist_array?
  • 您是否在某处为hist_array 中的指针分配了内存?如果不是 - 这就是段错误的原因。

标签: c segmentation-fault malloc strcpy


【解决方案1】:

问题在于以下语句 -

strcpy(hist_array[history_counter], temp);

strcpy 尝试将temp 指向的缓冲区复制到hist_array[history_counter] 指向的缓冲区,但char *hist_array[20];hist_array 定义为一个包含20 个字符指针的数组。您应该将您的功能更改为 -

char *hist_array[20];
int history_counter = 0;

void save_to_history(char *temp) {
    // +1 for the terminating null byte as strlen
    // does not count the null byte

    hist_array[history_counter] = malloc(1 + strlen(temp)); 
    if(hist_array[history_counter] == NULL) {
        printf("not enough memory to allocate\n");
        // handle it
    }
    strcpy(hist_array[history_counter], temp);
    printf("Saved %s to history to %d\n\n",
           hist_array[history_counter], 
           history_counter);

    history_counter++;
}

【讨论】:

    【解决方案2】:

    在您的代码中,您通过malloc 进行分配,但您没有对其进行初始化。所以当你这样做时:

    printf("temp = %s\narray = %s",temp,hist_array[history_counter]);/*debug*/
    strcpy(hist_array[history_counter],temp);
    

    应该打印一些垃圾,随后的 strcpy 将复制当时 temp 中的任何内容,直到遇到 0 字节。您在这里调用了未定义的行为,因为您应该初始化内存。

    例如你可以这样做:

    memset(temp, 0, 512);
    

    此外,您正在取消引用数组hist_array 中的指针。由于这是一个全局变量,所有指针最初都是 NULL 指针,这会导致您的 segfaul 出现。

    【讨论】:

      猜你喜欢
      • 2015-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 2017-02-25
      • 2016-07-12
      • 2018-03-16
      • 1970-01-01
      相关资源
      最近更新 更多