0

Hi I am writing a simple C program using "struct". I am trying to add strings (which always seems to be trouble) and I finally get to compile but when I run it I get an error. The file name is "struct" this is the error:

*** stack smashing detected *** ./struct terminated
Aborted (core dumped)

Here is the code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>


struct members {

    int  id;
    int  age;
    char name[];
};
int main(void)
{
    struct members person;
    person.id = 1223;
    person.age = 37;
    strcpy(person.name, "Matthew");

    printf("ID: %d\n Age: %d\n Name: %s\n", person.id, person.age, person.name);

return 0;
}

I have no idea why it's compiling fine then crashing. I guess it's a memory problem with the code in relation to the string. Funny thing is that it actually works and prints the info to console and then it crashes. Any help is appreciated. Thanks.

DGwang
  • 159
  • 1
  • 14
  • because `char name[]` is like doing `const char *` you should just assign directly to it like `person.name = "Matthew"` – Ryan Jan 31 '16 at 21:55
  • 2
    "compiles correct" does not imply the program **is** correct. If you manage to write a tool which can ensure that, you solved the _halting problem_ and are top-candidate for a turing award. – too honest for this site Jan 31 '16 at 21:57
  • http://stackoverflow.com/q/12680946/3185968 – EOF Jan 31 '16 at 22:30

3 Answers3

0

Try this. You are not allocating memory for name.

struct members {

    int  id;
    int  age;
    char * name;
};
...
person.name=strdup("Matthew");
goCards
  • 1,388
  • 9
  • 10
0

You have no memory allocated to the name element of struct members. When doing the strcpy you will be writing outside the stack memory where person was placed, "smashing" the stack.

You need to allocate memory to the name element, either statically by declaring it

char name[20];

or better, dynamically in main() using

persons.name = calloc(1, strlen("Matthew") + 1);
Aderstedt
  • 6,301
  • 5
  • 28
  • 44
0

the problem is no room in struct, nor elsewhere, to hold the characters of the string "Mathew".

regarding this line:

char name[];

suggest changing to:

char *name;

then, since there is no allocation for the actual bytes of the data, only a pointer, to set it via a pointer. I.E.

person.name = strdup( "Mathew" );

Of course remember, before exiting main() to pass that pointer to free()

free( person.name );

A second, (BUT IMO: less desirable technique as do not know the max length needed) could change the struct definition to:

struct members 
{
int  id;
int  age;
char name[100]; // arbitrary size, but must be large enough to hold max name string, including NUL termination byte
};

then the current code will work:

strcpy(person.name, "Matthew");
user3629249
  • 16,402
  • 1
  • 16
  • 17