【问题标题】:Strcpy segfaults after MallocMalloc之后的Strcpy段错误
【发布时间】:2016-01-25 00:43:54
【问题描述】:

所以,我在 C 中编写了一个简单的切片函数,它接受一个字符串数组、标记切片开始的字符串以及切片的大小。在函数中我 malloc 一个新数组,然后继续将切片中的每个字符串复制到新数组。然而,我在第一个 strcpy 上得到了一个段错误,即使我已经为结果数组分配了空间。

代码如下所示:

char** slice(char** args, char* start, int size){
  int i = 0;
  // need to find start first
  char* cursor = args[0];
  int j = 0;
  while(cursor != NULL){
    if(strcmp(cursor, start) == 0){
      break;
    }
    j++;
    cursor = args[j];
  }
  char** result = malloc(MAX_INPUT * size);
  while(i < size){
    strcpy(result[i], args[j+i]);
    i++;
  }
  return result;
}

导致段错误的行是--

strcpy(result[i], args[j+i]);

我使用 gdb 来查看结果和 args 中的值, result[i] 是 0x0,它是 NULL,但结果本身是一个地址,但我不确定为什么 malloc 不起作用。我的堆栈空间用完了吗?这是否意味着我被搞砸了?

【问题讨论】:

  • 这是一个关于运行时问题的问题,因此发布的代码必须干净地编译,并在运行时显示问题。发布的代码缺少#include 头文件语句,并且没有函数 I.E. 的驱动程序。没有 main() 函数,没有 'args[]' 参数内容的描述,也没有示例输入。由于问题似乎与“argss []”参数有关,因此需要发布设置该参数的代码
  • 贴出的代码无法检查 (!=NULL) 返回值,那么你怎么知道 malloc() 失败了?
  • MAX_INPUT 的#define 是什么? 'size' 与 'args[]' 参数有何关系?

标签: c arrays segmentation-fault malloc strcpy


【解决方案1】:

result[i] 是一个未初始化的指针。您犯了与以下相同的错误:

char *ptr;
strcpy(ptr, args[j+i]);

您必须使result[i] 指向某个分配的空间,然后才能将字符复制到其中。此外,MAX_INPUT * size 为指针数组分配的空间量是错误的。

另一个问题是,如果size 大于start 之后数组中剩余的字符串数,那么你会读取数组的末尾。

那么你的函数永远不会在新数组的末尾放置一个NULL,所以调用者无法知道你返回的切片有多大。

另外cursor 是多余的,你可以直接写args[j]。基本上功能是一团糟。

代码可能是(警告:未经测试):

char** slice(char** args, char const *start, int slice_size)
{
// Find index of "start"
    int start_index;

    for (start_index = 0; args[start_index]; ++start_index)
         if ( !strcmp(args[start_index], start) )
              break;

// Abort if "start" was not present (remove this line if you want to
// instead return an empty terminated list)
    if ( !args[start_index] )
         return NULL;

// Allocate array of pointers to new strings, allowing space for terminator
    char **result = malloc((slice_size + 1) * sizeof *result);
    if ( !result )
        return NULL;

// Copy strings in, allocating space for each string, stopping if no more args
    int i;
    for (i = 0; i < slice_size && args[start_index + i]; ++i)
         result[i] = strdup(args[start_index + i]);

// Terminate the list
    result[i] = NULL;

    return result;
}

【讨论】:

  • 谢谢!这行得通。是的,我想光标是不必要的,。
【解决方案2】:

这一行:

char** result = malloc(MAX_INPUT * size);

mallocs MAX_INPUT 个字符乘以大小。 'size'的内容是什么意思。

总的来说,我需要的是一个用于多个 char * 的 malloc,我在代码中没有看到。

然后,在得到正确的 malloc 参数后,

代码需要为每个字符串使用strdup()而不是strcpy()-或- malloc 空间,然后使用strcpy(),可能在包含两个函数调用的循环中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-05
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    • 1970-01-01
    • 2020-02-06
    • 2011-07-18
    相关资源
    最近更新 更多