0

I keep getting this Error: access violation at 0x40496a: write of address 0x0. I'm using Borland C++.

This is my source code.

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
int main()
{
    char *nm;
    cout<<"\n Enter a name: ";
    gets(nm);
    cout<<"\n Name: "<<nm;
    getch();
    return 0;
}

Even if I set char *nm=NULL or use cin>> for input I'm getting the same error. Please Help, Thanks.

Pramod Gupta
  • 53
  • 1
  • 7

1 Answers1

4

When you declare nm you don't initialize it, that means the value of nm is indeterminate, it doesn't really point anywhere (in reality it points to a seemingly random location). You need to make it point to something big enough to hold the string you input.

Using uninitialized variables, and NULL pointers, leads to undefined behavior whose most common result is a crash.

To fix this, either make it point to an already initialized array:

char str[20];
char* nm = str;

Or allocate memory for the string dynamically:

char* nm = new char[20];

Or even better, don't use character pointers as string, and especially not the gets function (it's dangerous and have even been removed from the C standard), use the C++ std::string class instead and std::getline function to fetch a line:

std::string nm;
std::getline(std::cin, nm);

Or if you just want to get a single space-delimited word, use the normal input operator:

std::string nm;
std::cin >> nm;
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thanks, I understood what was the mistake, I just on more confusion, what is meaning of std::string nm; I think it means string belongs to std class ? I'm getting confused because I have never used this syntax. please help – Pramod Gupta Sep 07 '14 at 18:59
  • 1
    @PramodGupta [This](http://stackoverflow.com/q/388242/1870232) is a nice place to start with. – P0W Sep 07 '14 at 19:04
  • @PramodGupta It's probably because you use such an old version of C++ (I'm guessing you are using TurboC++?). Quite a lot have happened with the C++ language and its runtime library in the last 20 or so years, which means that unfortunately all you are learning at school with TurboC++ already is useless for use in the real world. – Some programmer dude Sep 07 '14 at 19:16
  • 1
    @PramodGupta My advice is for you to continue your schoolwork with TurboC++, but if you really want to learn C++ then you should install e.g. [Visual Studio Express](http://www.visualstudio.com/en-us/products/visual-studio-express-vs.aspx) or some other free modern environment, and follow the link in P0Ws comment for some better tutorials and references, and work on those at home. – Some programmer dude Sep 07 '14 at 19:17