-2

So I have this code:

#include <iostream>
#include <string.h>

using namespace std;

struct helloworld {
    char name[1];
};

main() {
    struct helloworld test[2];
    strcpy(test[0].name, "No .1");
    strcpy(test[1].name, "No .2");
    for (int integer = 0; integer < 2; integer++) {
    cout << test[integer].name << endl;
    }
}

and I save it to a file called test.cpp. To compile the file, I do

g++ -o main test.cpp

Then when I run ./main this is the output I get

NNo .2
No .2

This is the expected output

No .1
No .2

Any ideas of why I am getting this error how to fix this bug?

  • 1
    You are writing in memory you don't own. Use `strncpy`. – lared Feb 12 '15 at 00:58
  • 2
    You've defined `name` as a single character array, and you're putting more than a single char into it. IOW, you've overrun the bounds of the array, and the behavior is undefined. – Ken White Feb 12 '15 at 00:59
  • 2
    Undefined behavior / buffer overrun. You allocate an array of 1 character, but you copy 6 characters (nul terminator inclusive) to the array. Look out for Nasal Demons! – Thomas Matthews Feb 12 '15 at 00:59
  • Alright, thank you Axalo. I found the answer in the article. You too lared. – user3719066 Feb 12 '15 at 01:00
  • @lared `strncpy` is just as easy to misuse as `strcpy`. If you have to use c strings, `sscanf` is more powerful, easier to use, and safer than `strncpy`/`strcpy`. – Red Alert Feb 12 '15 at 01:05

1 Answers1

0

You are copying too many characters into a char array of size 1. Make your char name[1] bigger (e.g. 10 or so for this example).

Better yet, use std::string instead.

edtheprogrammerguy
  • 5,957
  • 6
  • 28
  • 47