【问题标题】:Trying to copy all strings from char*[] but get segmentation fault试图从 char*[] 复制所有字符串但出现分段错误
【发布时间】:2017-12-09 05:58:45
【问题描述】:

我试图弄清楚为什么在尝试将参数从一个字符串数组复制到另一个字符串数组时出现分段错误,但只是省略了 >

int main(){
     char *args[] = {"sort", "myshell.c", ">", "2"};
     int size = 4*sizeof(args)/sizeof(args);
     char *temp[size];
     int i;

     printf("SIZE: %d\n", size);
     for(i = 0; i < size; ++i){
            if(strcmp(args[i], ">") > 0 || strcmp(args[i], ">") < 0 ){
                strcpy(temp[i],args[i]);

            }
            printf("arg: %s\n", temp[i]);
     }

【问题讨论】:

  • 4*sizeof(args)/sizeof(args);同一个数相乘除除的目的是什么?
  • 是的,我刚刚注意到。抱歉,愚蠢的错误,还在学习中

标签: c arrays string shell segmentation-fault


【解决方案1】:
strcpy(temp[i],args[i]); 

这是未定义的行为。 strcpy 尝试访问不确定的内存位置,从而导致未定义的行为。

你需要分配内存给temp[i]或者干脆使用

temp[i]=strdup(args[i])

将字符串复制到temp[i]

还有

int size = 4*sizeof(args)/sizeof(args);

int size = sizeof(args)/sizeof(*args);

如果您知道数组的长度为 4,那么进行所有这些计算有什么用。你需要计算它而不是那样说。

示例代码:-

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
     char *args[] = {"sort", "myshell.c", ">", "2"};
     size_t size = sizeof(args)/sizeof(*args);
     char *temp[size];
     size_t len = 0;
     printf("SIZE: %zu\n", size);
     for(size_t i = 0; i < size; ++i){
            if(strcmp(args[i], ">") != 0 ){
                temp[len++] = args[i];
            }
     }
     for(size_t i = 0; i < len; i++){
        printf("arg[%zu]: %s\n", i+1, temp[i]);
     }
     return 0;
 }

请注意,如上所述,您的比较应该更简单。

strdup 是做什么的?

它在内部分配内存,然后使用strcpy 复制目标字符串。这不是标准库的一部分,由 POSIX 实现。 有关更多详细信息,请查看此answer

【讨论】:

  • 我通过使用你提到的那个函数 strdup() 修复了它,但我不知道为什么?它是如何工作的?
  • @CodeDexter.:我已经提到了参考和一个总体思路。希望能帮助到你。检查答案
【解决方案2】:

您的代码在 strcpy(temp[i],args[i]); 处崩溃,因为 temp[i] 具有未初始化的值。在调用strcpy之前,您需要分配内存并将地址存储在temp[i]

【讨论】:

    【解决方案3】:
    1. 您正试图将数据(在本例中为字符串)复制到 temp[i] 指向的内存中 - 但此指针未初始化且未分配内存。 你应该分配内存:

      temp[i] = (char <em>)malloc(sizeof(char)</em>(strlen(args[i])+1))

    2. 要省略 ">",您只需测试 != 0。您需要为复制的字符串设置二级索引。

    3. sizeof(args)/sizeof(args)的目的是什么? 试试:

      int main()
      {
           char *args[] = {"sort", "myshell.c", ">", "2"};
           int size = sizeof(args)/sizeof(char *);
           char *temp[size];
           int i, j;
      
           printf("SIZE: %d\n", size);
           for (j = 0, i = 0; i < size; ++i)
           {
                  if (strcmp(args[i], ">") != 0)
                  {
                      temp[j] = (char *)malloc(sizeof(char)*(strlen(args[i])+1));
                      strcpy(temp[j],args[i]);
                      printf("arg: %s\n", temp[j]);
                      j++;
                  }
           }
      }
      

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 1970-01-01
      • 2014-11-01
      • 2013-12-06
      • 2012-06-17
      • 2020-10-02
      • 2012-06-25
      • 2011-09-03
      • 1970-01-01
      相关资源
      最近更新 更多