Search code examples
cpointerscharstack-smash

Stack smashing in C on function return


I have a small program which converts 12 hour time to 24 hour time.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

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;
}

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.


Solution

  • Function get_tokens writes into stack-allocated buffer with 3 pointers without checking for buffer capacity constraint. fields[num_f] = strtok will potentially cause a stack buffer overrun. And at the same time fields items could be used uninitialized.

    There is also a memory leak since you never free allocated memory.