0

I’m studying flexible array members. I've written the code below based on a 2 line example in the book I'm studying from. The code compiles with gcc -Wall with no errors and also executes without error.

However I don’t know what the (n) at the end of this malloc call is for. I assume if I'm storing a string the the flexible array, I'm supposed to call strlen() on the string and use the returned value for (n). The code seems to work no matter what value I assign to (n) and even works when there is no (n).

struct vstring *str = malloc(sizeof(struct vstring) + n);

Is the value needed or not?

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

struct vstring{
  int len;
  char chars[];  /* c99 flexible array member to store a variable string */
};

int main()
{
  char input_str[20];
  int n = 0; /* what should n be it doesn’t seem to matter what value I put in here */
  struct vstring * array[4]; /* array of pointers to structures */

  int i = 0;
  while ( i < 4 )
  {
    printf("enter string :");
    scanf("%s",input_str);
    struct vstring *str = malloc(sizeof(struct vstring) + n );
    strcpy(str->chars,input_str);
    str->len  = strlen(input_str);
    array[i] = str;
    i++;
  }

  for ( i = 0 ; i < 4 ; i++) {
    printf("array[%d]->chars = %s len = %d\n", n, array[i]->chars, array[i]->len);
  }

  return 0;
}
1
  • use fgetsfor strings its better :) Commented Sep 27, 2014 at 13:37

1 Answer 1

2

Yes, you need to allocate enough memory to store your string. So n on your case should be

strlen(input_str)+1.

What you are doing is writing into unallocated memory and invoking undefined behaviour. The code might work, but it is wrong.

You also have a typo(?) in your malloc call. It should be

struct vstring *str = malloc( sizeof(struct vstring) + n );

And don't forget that inputting more than 19 characters with the scanf call will also cause undefined behaviour as you will write out of bounds of your array. You could avoid that with %19s as the conversion specification. You should also check that the scanf() was successful.

Sign up to request clarification or add additional context in comments.

3 Comments

can you explain also what is the need of having nested sizeof operators in this case?
The nested sizeof operator is a typo from when I typed in the example from the book,
Thanks user2501 the "writing into unallocated memory" explanation makes sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.