将新值分配给char *变量时访问冲突

时间:2019-04-19 04:02:22

标签: c pointers char

我正在测试以下代码,但是执行此行时出现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;
}

2 个答案:

答案 0 :(得分:3)

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

由于port指向字符串文字中的字符之一,因此尝试通过以下方式修改该值:

*port = 0;

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

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

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

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

答案 1 :(得分:0)

char *port = strchr(host, ':');

在主机字符串中产生指向':'的指针,并且由于您定义了文字字符串

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;
}