简体   繁体   English

Linux分段错误

[英]Linux segmentation fault

When I run this program I get segmentation fault, and I could not find it's origin. 当我运行该程序时,出现分段错误,并且找不到它的来源。 I don't know how to deal with it. 我不知道该如何处理。 Could you help me? 你可以帮帮我吗?

This is my code. 这是我的代码。

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

    static int func(int argc, char * argv[])
    {
      char msg[500]="sdfsdf";

      argv[0]="sdf grgrg";

      printf("%s",argv[0]);

      argv[0]='\0';

      strcpy(argv[0],msg);

      printf("%s",argv[0]);

      return 0;
    }

    int main(int argc, char* argv[])
    {
      func(argc, argv);
      //printf("sdfasf");
    }

Let's focus on these lines. 让我们专注于这些行。

argv[0]='\0';
strcpy(argv[0],msg);

It's irrelevant that this is argv[0] , so I'll introduce a variable: 这是argv[0]无关紧要,因此我将介绍一个变量:

char *var = '\0';
strcpy(var, msg);

Then, recall that '\\0' is an integer literal with value zero, so when it is assigned to a pointer variable it becomes a null pointer: 然后,回想一下'\\0'是值为零的整数文字,因此当将其分配给指针变量时,它将变为空指针:

char *var = NULL;
strcpy(var, msg);

We can inline the variable: 我们可以内联变量:

strcpy(NULL, msg);

Whoops! 哎呦! Don't do that. 不要那样做 That will crash, or worse--it might not crash. 那会崩溃,或更糟的是,它可能不会崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM