How to use strdup and strcat in C

34 Views Asked by At

I am trying to concatenate two string in C

Here is my program, server->vhost.root_dir is char * initialized with strdup.

        char *path = strdup(server->vhost.root_dir);                            
        if(path == NULL)                                                        
        {                                                                       
             return;                                                             
        }                                                                       
        path = strcat(path, request.Request_target);                            
        if (path == NULL)                                                       
        {                                                                       
             return; 
        }                                                            

But i am getting a heap buffer overflow. What is wrong in my program ?

Here is the error i am getting when i am using the flag fsanitize

=================================================================
==21902==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6030000002ce at pc 0x7f9ab9eec590 bp 0x7ffdb40ffa60 sp 0x7ffdb40ff210
WRITE of size 6 at 0x6030000002ce thread T0
    #0 0x7f9ab9eec58f in __interceptor_strcat (/run/current-system/sw/lib/libasan.so.6+0x3d58f)
    #1 0x404f92 in get_method src/request.c:129
    #2 0x405e51 in start_server src/server.c:175
    #3 0x402646 in main src/main.c:32
    #4 0x7f9ab9cda236 in __libc_start_call_main (/run/current-system/sw/lib/libc.so.6+0x29236)
    #5 0x7f9ab9cda2f4 in __libc_start_main_impl (/run/current-system/sw/lib/libc.so.6+0x292f4)
    #6 0x4023f0 in _start (/afs/cri.epita.fr/user/n/ni/nicolas.schmitt/u/httpd/epita-ing-assistants-acu-httpd-2025-strasbourg-6/httpd+0x4023f0)

0x6030000002ce is located 0 bytes to the right of 30-byte region [0x6030000002b0,0x6030000002ce)
allocated by thread T0 here:
    #0 0x7f9ab9f0b7a7 in strdup (/run/current-system/sw/lib/libasan.so.6+0x5c7a7)
    #1 0x404f42 in get_method src/request.c:124
    #2 0x405e51 in start_server src/server.c:175
    #3 0x402646 in main src/main.c:32
    #4 0x7f9ab9cda236 in __libc_start_call_main (/run/current-system/sw/lib/libc.so.6+0x29236)
    #5 0x7ffdb4102237  ([stack]+0x20237)
    #6 0x747261747300612c  (<unknown module>)

0

There are 0 best solutions below