Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the errors in this function from a Microsoft interview question?

Tags:

c

string

I was asked this question in the MS written walkin-interview:

Find errors in the program below which is supposed to return a new string with \n appended to it.

char* AddnewlinetoString(char *s)
{
  char buffer[1024];
  strcpy(buffer,s);
  buffer[strlen(s)-1] = '\n';
  return buffer;
}

I'd tried to code on myself and was able to get it working by making buffer variable global and having buffer[strlen(s)] = '\n'. But did not know there were many other bugs in it.


2 Answers

I can see a few:

Length of input string not checked.

What if the strlen(s) > 1023? You can fit a string of length at most 1023 in buffer.

Overwriting the last char with \n

You are overwriting last char with newline. Your \n should go where \0 used to be and you need to add a new \0 after \n

Variable buffer is local to function and you are returning its address.

Memory for buffer is allocated on stack and once the function returns, that memory is freed.

I would do:

char* AddnewlinetoString(char *s) {

  size_t buffLen = strlen(s) + 2; // +1 for '\n' +1 for '\0'
  char *buffer = malloc(buffLen); 
  if(!buffer) {
   fprintf(stderr,"Error allocting\n");
   exit(1);
  }
  strcpy(buffer,s);
  buffer[buffLen-2] = '\n';
  buffer[buffLen-1] = 0;
  return buffer;
}
like image 157
codaddict Avatar answered Sep 12 '25 20:09

codaddict


  1. there's no limit in strcpy, better use strncpy.
  2. you are copying to static buffer and returning pointer.
like image 39
Tomasz Kowalczyk Avatar answered Sep 12 '25 20:09

Tomasz Kowalczyk