Dear friends
Im new in IT and i want to ask you about boundary values check in a program.
I have the following exercise that I want to check and i don't know how...

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

struct st {
       int i;
       char n[4];
       char g;
struct st C;

int F(char *fe){

	if (fe == NULL)
    C.g = 'OLE'; //only this value is allowed
    strncpy( C.n, fe, strlen(fe));

Please help me only with the way out, i have to try it myself.
Thanks allot in forward

9 Years
Discussion Span
Last Post by Nektarios

The check should be to prevent the user of the function from passing in a string that is too long to fit in st.n[] .


/* Make sure the string is null-terminated */
  memset( (void *)C.n, '\0', sizeof(C.n) );

  /* Copy the string over, leaving room for null */
  strncpy( C.n, fe, sizeof(C.n) / sizeof(C.n[0]) );

This code makes use of a simple trick to have the compiler calculate the right constant values to use. The sizeof operator returns the number of bytes that an object uses.

memset() fills a specific number of bytes. So sizeof(C.n) is appropriate.

strncpy() copies a specific number of characters. To calculate the number of characters, we use sizeof(C.n) / sizeof(C.n[0]) , which is the same as (total number of bytes) / (bytes per element), which is the number of elements (or chars) in the array.


This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.