3

my project is to build book structure - and fill it with users parameters.

involving dynamic allocation, arrays and pointers.

my book structure has the following:

struct BOOK
{
    char* author;
    char** genders;
    int totalGenders;
    char* name;
    int* chapterPages;
    int totalChapters;

}typedef book;

when I tried reaching author name, line 1 in structure:

struct BOOK
{
    char* author;

I failed doing that.. my code in main :

int main()
{
    book* b;
    char authorChar[10] = { 0 };
    int authorLen;
    char* authorName;


    // get author name
    puts("please enter the name of the author");
    scanf("%s", &authorChar);
    authorLen = strlen(authorChar);
    printf("%d", authorLen);    //print to see that lentgh is correct.

    authorName = (char*)calloc(authorLen, sizeof(char));
    strcpy(authorName, authorChar);
    puts("\n");
    b->author = authorName;

    printf("%d", b->author);

when i have debugged i got a problem in this line :

b->author = authorName;

ideas please? :)

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Moshe
  • 461
  • 1
  • 5
  • 15

2 Answers2

3

The problem is in the following line

  b->author = authorName;

at this point, b is not allocated memory, i.e., b is an uninitialized pointer. It points to some random memory location which is not a valid one. Any attempt to access invalid memory invokes undefined behavior.

You can use either of the following approach to resolve the issue:

  • allocate memory to b dynamically before using it, like b = malloc(sizeof*b); and a check for success.

  • define b as a variable of type book, instead of a pointer-to-type.

That said, int main() should be int main(void) at least, to conform to the standards.

Ziezi
  • 6,375
  • 3
  • 39
  • 49
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • thank you for your answer ! , my mistake really began when i defined `b` to be a pointer-to-type, without initialize it. (i did it because in the further future, book struct will be just one of - books array...). – Moshe Jan 13 '16 at 11:28
1

You are forgetting to do the memory allocation for b variable.

b = malloc(sizeof(book));
b->author = malloc(sizeof(100000)); // replace value for the size you want
Mohan
  • 1,871
  • 21
  • 34
Victor Viola
  • 575
  • 1
  • 4
  • 14