简体   繁体   中英

CPP access violation Error

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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