【问题标题】:Access Violation when assign new value to char* variable为 char* 变量分配新值时访问冲突
【发布时间】:2019-04-19 04:02:21
【问题描述】:

我正在测试下面的代码,但是当执行时,这一行中出现了一个 AV:

*port = 0;

如何解决这个问题?我做错了什么?

#include "stdafx.h"
#include <windows.h>
#include <conio.h>

int _tmain(int argc, _TCHAR* argv[])
{
    char *host = "127.0.0.1:1234";
    char *port = strchr(host, ':');

    if (port)
    {
        *port = 0;
        ++port;
        printf("%s \n", *port);

        int portInt = strtol(port, NULL, 10);

        printf("%d: \n", portInt);
    }

    getchar();

    return 0;
}

【问题讨论】:

  • 您也不需要所有代码来复制错误。修改字符串文字是未定义的行为。即int main() { char *p = "abc"; p[0] = 'x'; }——同样的问题。

标签: c pointers char


【解决方案1】:

问题在于您正在尝试修改字符串文字 (host)。字符串文字是const,因此尝试修改一个是未定义的行为。

由于port 指向字符串文字中的一个字符,因此尝试通过这样做来修改该值:

*port = 0;

导致未定义的行为,在您的情况下是崩溃。

一种解决方法是简单地将host 设为char 的数组:

char host[] = "127.0.0.1:1234";
char *port = strchr(host, ':');

由于声明已更改为host 的数组,因此该数组中的所有字符都可以修改。

【讨论】:

    【解决方案2】:
    char *port = strchr(host, ':');
    

    产生一个指向 ':' in 的指针,因为你定义了一个文字字符串

    char *host = "127.0.0.1:1234";`
    

    host 是一个指向只读内存位置的指针,因此

    *port = 0;
    

    实际上尝试写入只读的host 字符串。

    你可以写:

    int _tmain(int argc, _TCHAR* argv[])
    {
      // define a const as const
      const char *host_default = "127.0.0.1:1234";
    
      // dup host if you want to write in it, or change.
      char *host=strdup(host_default);
    
      if (!host) exit(-1); // check if memory was allocated!
    
      // port pointer to `:` in memory of host String
      char *port = strchr(host, ':');
    
      if (port)
      {
        *port = 0; // have host to be Null terminated
        ++port;
        printf("%s \n", port);
    
        long portInt = strtol(port, NULL, 10);
    
        printf("Port: %ld: \n", portInt);
        // I can only assume you also want the hostname, seen the *port = 0;
        printf("HostName: %s: \n", host);
      }
      // free allocated memory;
      free(host);
      // set to NULL, good practise
      host=NULL;
      // set port also to NULL as it might point to released memory of host
      port=NULL;
    
      getchar();
    
      return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-06
      • 1970-01-01
      • 1970-01-01
      • 2019-05-25
      • 2017-04-22
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多