title: Stack smashing in C on function return
body: <p>I have a small program which converts 12 hour time to 24 hour time. </p>
  
  <pre><code>#include &lt;math.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;assert.h&gt;
  #include &lt;limits.h&gt;
  #include &lt;stdbool.h&gt;
  
  int get_tokens(char* buf, char *fields[], char *sep){
  
      char* ptr= (char*)malloc((10*sizeof(char))+1);
          strncpy(ptr, buf, 10);
          *(ptr+10)='\0';
      int num_f=0;
  
      while((fields[num_f] = strtok(ptr,sep)) != NULL ){
          ptr = NULL;
          num_f++;
      }
      return num_f;
  }
  
  
  char* timeConversion(char* s) {
      char *fields[3];
      int num_f=0;
      char *ptr = (char*) malloc(100*sizeof(char));
      int hour=0;
  
      get_tokens(s, fields, ":");
      if(strstr(s,"PM")){
          hour=atoi(fields[0])+12;
      }
      else{
        hour=atoi(fields[0]);
      } 
  
      snprintf(ptr, 9, "%d:%s:%s" ,hour,fields[1],fields[2]);
      return ptr;
  }
  
  int main() {
      char* s = (char *)malloc(100 * sizeof(char));
      scanf("%s", s);
      char* result = timeConversion(s);
      printf("%s\n", result);
      return 0;
  }
  </code></pre>
  
  <p>I see a "stack smash" immediately after the timeConversion function returns. 
  I know that the logic of the code works but am not able to figure out the stack smash.</p>