Assaf Karavani
Assaf Karavani

Reputation: 81

C structures and pointers

This is my struct:

typedef struct Person {

    char* name;
    int age;
    float height;
    float weight;
    char** hobbies;

}person;

I tried to fill the name but it just ain't working.

void main(){

    person Asaf;
    char buffer[50];
    int length;

    puts("Please enter the name of the student");
    gets(buffer);
    length = strlen(buffer);
    Asaf.name = realloc(buffer, length);

}

I just can't figure the problem... I guess it has something to do with the realloc function. please help!! :P

Upvotes: 0

Views: 77

Answers (2)

jschultz410
jschultz410

Reputation: 2899

You are trying to realloc (which operates on the heap) an array that is allocated on the stack, which is a no-no. What you want instead is something like:

Asaf.name = strdup(buffer);  /* POSIX: allocates a string copy of buffer on the heap */

Or, more standardly:

Asaf.name = (char*) malloc(strlen(buffer) + 1);  /* TODO: should check allocations for NULL return */
strcpy(Asaf.name, buffer);

Also, you should use fgets() rather than gets(). gets() is inherently dangerous and should never be used because it doesn't do any bounds checking on the array to which it writes.

fgets(buffer, sizeof(buffer), stdin);

Upvotes: 3

Sumit Singh
Sumit Singh

Reputation: 310

This function returns a pointer to the newly allocated memory, or NULL if the request fails.

so as realloc operates on heap here getting pointer to the memory allocation in heap area to a pointer guy sitting in stack can cause some problems buddy. so maybe undefined behavior can be the answer for the output you are getting.

About how using realloc, all the didactic examples include this- Use realloc:
1>Check if it's NULL.In this case use perror and exit the program
2>If it's not NULL use the memory allocated
3>Free the memory when you don't need it anymore.

possible duplicate of:How to use realloc in a function in C

Upvotes: 0

Related Questions