c - 操作字符串时出现段错误?

标签 c string segmentation-fault

这段代码总结了我遇到的问题。我想将文件从源复制到指定的目的地,我可以更改它的名称,它是集成在我试图创建的应用程序中的函数管理文件

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

 void concatenate_string(char *original, char *add)
{
   while(*original!='\0')
     original++;

   while(*add!='\0')
     {
        *original = *add;
         add++;
         original++;
     }
     *original = '\0';
}

 int main(int argc,char *argv[])
  {

    char *nom;
    char *path;
    printf("entrer a name \n");
    scanf("%s",nom);
    printf("entrer a pathh \n");
    scanf("%s",pathh);
    char *dest=(char*)malloc(strlen(nomm)+46+1);
    strcat(dest,"/home/ridaamine/Desktop/app/application/Files/");
    strcat(dest,nom);
    char *comand=(char*)malloc(strlen(name)+8+strlen(path)+1);
    strcat(comand,"cp -via ");
    strcat(comand,path);
    strcat(comand," ");
    strcat(comand,name);
    system(comand);
  }

最佳答案

您没有初始化nom

scanf("%s",nom);

或者

nom = malloc(SOME_SIZE);

然后,假设SOME_SIZE == 100

scanf("%99s", nom);

char nom[SOME_SIZE];

然后,我们还可以说SOME_SIZE == 100

scanf("%99s", nom);

当然这同样适用于路径

第二个解决方案更好,因为它更快没那么快并且使用后您不需要free(nom)。在极少数情况下可能需要第二种情况,即字符串的大小太大(> 8M)以至于会溢出堆栈。

正如Weather Vane指出的strcat也有问题,你应该使用strcpy 第一次

strcat(dest,"/home/ridaamine/Desktop/app/application/Files/");
strcat(dest,nom);

应该是

strcpy(dest,"/home/ridaamine/Desktop/app/application/Files/");
strcat(dest,nom);

显然这一次,同样适用于命令

终于有了一个你没有算进去的空间

malloc(strlen(dest) + 8 + strlen(path) + 1 + 1 /* space " " */)

提示:您不需要强制转换malloc,所以不要这样做,它可能会隐藏潜在的错误。在取消引用指针之前,请始终检查 malloc 是否返回 NULL

完成后你也应该调用 free,这是你自己的代码修复

 int main(int argc,char *argv[])
  {

    char nom[100];
    char path[100];
    char _path[] = "/home/ridaamine/Desktop/app/application/Files/";
    char cp[] = "cp -via ";
    char space[] = " ";

    printf("entrer a name \n");
    scanf("%99s", nom);
    printf("entrer a path \n");
    scanf("%99s", path);

    char *dest = malloc(strlen(nom) + strlen(_path) + 1);
    if (dest == NULL)
    {
        printf("no more memory left.\n");
        return -1;
    }       
    strcpy(dest, _path);
    strcat(dest, nom);

    char *comand = malloc(strlen(dest) + strlen(cp) + strlen(space) + strlen(path) + 1);
    if (command == NULL)
    {
        free(dest);
        printf("no more memory left.\n");
        return -1;
    }

    strcpy(comand, cp);

    strcat(comand, path);
    strcat(comand, space);
    strcat(comand, dest);

    free(dest);
    system(comand);
    free(command);

    return 0; // always return from main
  }

关于c - 操作字符串时出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27769559/

相关文章:

c - 在 C 中存储常量数据的最佳方法

c - 在我的字符串中获取垃圾

来自 argc 的 C 段错误

c - 无法使用 CS50 IDE 中的函数创建程序

c++ - 在独立的 Xcode playground 中运行 c 或 c++ 代码

c++ - 如果函数返回 std::vector<std::string> 是否存在内存泄漏?

c - 创建链表时出现段错误

c - FILE IO,标记字符串

无法存储 key : SYSTEM ERROR when running c program under cgi-bin

c - 使用 libtiff 在 C 中读取 .tif 图像返回一列