Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

failed while trying to reach pointer in struct

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? :)

like image 671
Moshe Avatar asked Sep 21 '26 17:09

Moshe


2 Answers

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.

like image 154
Sourav Ghosh Avatar answered Sep 24 '26 01:09

Sourav Ghosh


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
like image 36
Victor Viola Avatar answered Sep 24 '26 01:09

Victor Viola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!