c - Why do I get a segmentation fault when I try to add a NUL terminator at the end of my string? -


according gdb, segmentation fault when try assign '\0' last position in request_line. can't use memory on heap (alloc, malloc, calloc) since server implementation control handlers can make hard free space.

the size of request_targetsize 24, correct.

#include <string.h> #include <stdio.h>  int main() {    const char line[80] = "get /index.html/search?q=cat http/1.1";    char *abs_path;    char *str = null;    char *request_target= null;    char *query = null;      //get request target    char* startofrequest_target = strchr(line, '/');    char* endofrequest_target = strchr(startofrequest_target, ' ');    int request_targetsize = endofrequest_target - startofrequest_target;    if (startofrequest_target != null && endofrequest_target != null)     {        memcpy(request_target, startofrequest_target, request_targetsize);        request_target[request_targetsize] = '\0';    } .... 

my guess has initializing request_target array null, error if don't.

why segmentation fault? also, why need assign char* variables null , not?

the problem see with

 memcpy(request_target, startofrequest_target, request_targetsize); 

here, request_target null , you're trying write it. invokes undefined behavior hence seg fault.

instead of making request_target pointer, consider using array,

char request_target[80]= {0}; 

Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -