title: C++ Sockets - Client gives segmentation fault (linux)
body: <p>I created a server/client connection. The server and client both are compiling correctly but when I run the client, it gives me a <code>Segmentation Fault (core dumped)</code></p>
  
  <p>I don't know what I am doing wrong with my memory allocations. The program is not dangling or anything. I think my program is writing to a read-only portion of the memory, or maybe accessing a memory that is not available.</p>
  
  <p>If anyone can tell where is the bug I would really appreciate it.</p>
  
  <p>client.cpp</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;string.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;netinet/in.h&gt;
  #include &lt;arpa/inet.h&gt;
  #include &lt;netdb.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;unistd.h&gt;
  using namespace std;
  
  int main() {
      char a;
      int client;
      int portNum = 1500;
      int bufsize = 1024;
      char* buffer = new char (bufsize);
      bool isExit = false;
      char* ip;
      strcpy(ip, "127.0.0.1");
  
  struct sockaddr_in direc;
  
  if ((client = socket(AF_INET, SOCK_STREAM, 0)) &lt; 0) {
      cout &lt;&lt; "Error creating socket..." &lt;&lt; endl;
      exit(0);
  }
  
  cout &lt;&lt; "Enter # to end call" &lt;&lt; endl;
  cout &lt;&lt; "\t\t\t[s] to begin with" &lt;&lt; endl;
  cin &gt;&gt; a;
  
  cout &lt;&lt; "Socket created successfully..." &lt;&lt; endl;
  direc.sin_family = AF_INET;
  direc.sin_port = htons(portNum);
  inet_pton(AF_INET, ip, &amp;direc.sin_addr);
  
  if (connect(client,(struct sockaddr *)&amp;direc, sizeof(direc)) == 0)
      cout &lt;&lt; "Connection to the server " &lt;&lt; inet_ntoa(direc.sin_addr) &lt;&lt; endl;
  
  cout &lt;&lt; "Awaiting confirmation from the server..." &lt;&lt; endl;
  recv(client, buffer, bufsize, 0);
  
  cout &lt;&lt; "Response received: " &lt;&lt; buffer;
  cout &lt;&lt; "\nRemember to put an asterisk at the end to send a message * \n Enter # to terminate the connection" &lt;&lt; endl;
  
  do {
      cout &lt;&lt; "Enter a message: ";
      do {
          cin &gt;&gt; buffer;
          send(client, buffer, bufsize, 0);
          if (*buffer == '#') {
              send(client, buffer, bufsize, 0);
              *buffer = '*';
              isExit = true;
          }
      } while (*buffer != 42);
  
      cout &lt;&lt; "Mensage received: ";
      do {
          recv(client, buffer, bufsize, 0);
          cout &lt;&lt; buffer &lt;&lt; " ";
          if (*buffer == '#') {
              *buffer = '*';
              isExit = true;
          }
  
      } while (*buffer != 42);
      cout &lt;&lt; endl;
  
  } while (!isExit);
  cout &lt;&lt; "Connection terminated. END PROGRAM\n\n";
  close(client);
  return 0;
  }
  </code></pre>
  
  <p>I am assuming you don't need the server.cpp since it's all good and waiting for incoming connections.</p>
  
  <p>Thanks!</p>