Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Memory error: what's wrong with strcpy(pattern,"\t")???

Status
Not open for further replies.

cadbilbao

Programmer
Apr 9, 2001
233
ES
Hello.

I've got a memory error when executing this piece of code compiled by Visual C++ (it does not happen in other compilers):

char *pattern;
strcpy(pattern,"\t");

There are no errors when compiling...

What am I doing wrong?
 
There is no space allocated for pattern

try

char pattern[16];
strcpy(pattern,"\t");

or dynamically allocate the memory with a malloc or new before you write to it.


Matt
 
The problem is: pattern is an uninitialized pointer. Because it is uninitialized, the value is random; because it is a pointer, it is thus randomly points to any memory location – including your program code area, data area, or system area. Program crashes is the least you would expect.

You have to initialize the pointer to a allocated memory:
Code:
    char *pattern = new char[2];  // you need one more space for the ‘\0’ character
    strcpy(pattern, "\t");    // char[0] is ‘\t’, char[1] is ‘\0’

or use a fixed size array like Matt suggested.

Shyan


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top