Question about default c grammar string segmentation error.

Asked 2 years ago, Updated 2 years ago, 26 views

    char* Req_topic[] = {0,};
    char Req_topic_SerialNumber[] = {0,}; 

    strcat(Req_topic_SerialNumber , "qqq/aaa/bbb/");
    strcat(Req_topic_SerialNumber, SERIALNUM);
    strcat(Req_topic_SerialNumber , "/cccc");

    printf("111\n");
    Req_topic[0] = Req_topic_SerialNumber;

    printf("222\n");

    printf("Req_topic : %s\n", Req_topic);

    printf("333\n");

When running the program after compiling (g++) as above

111

222

Req_topic : `­ vvbbb/SERIALNUM/cccc

333

./mm: line 3: 3783 Segmentation Error I don't understand why the previous string is broken and there is an error when it is executed like this, so I'm asking a question...

c c++

2022-09-21 20:31

1 Answers

By default, c language is difficult to process strings.

It's better if you go to c++ and you get a string class, but...c is hard to handle.

char* Req_topic[] = {0,};       
char Req_topic_SerialNumber[] = {0,}; 

Do not initialize as above.

char Req_topic_SerialNumber[255]; // Free memory to allocate 255 characters 

Make sure you have a buffer and add a string as shown above. This prevents segmentation faults.

If the buffer is not secured, the buffer overflow occurs as the string is added to the wrong area.

The lower part also needs to be modified.

printf("Req_topic : %s\n", Req_topic[0]);

Compared to modern languages, C language has many low-level elements, so you have to be careful when processing memory.


2022-09-21 20:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.