简体   繁体   中英

how can i insert a single char in front of my c string?

So on line 28 i make a c-string called temp. I assign the value of temp[0] to the value of string[index]. Now i want to add string to the end of temp and then make string store the same values as temp. i tried to use strcat() but it gives me a "buffer overflow detected". Are there any other solutions i can try, basically all i want is for "string = string[index] + string" if only that was possible in C. I need the program to run in a certain speed so i do not want to use a loop to fix this.

//Problem        : Expecto Palindronum
//Language       : C
//Compiled Using : GCC
//Version        : GCC 4.9.1
//Input for your program will be provided from STDIN
//Print out all output from your program to STDOUT

#include <stdio.h>
#include <string.h>

int main() {
    char string[202];
    char revstring[202];
    gets(string);
    int ilength = strlen(string);
    int index = ilength - 1;
    int i;
    for(i = 0; i<(ilength);i++){
        int y =  index - i;
        revstring[i] = string[y];
    }
    while(1==1){
        int length = strlen(string);
        if(strcmp(revstring,string)==0){
            printf("%d",length);
            break;
        }else{
            char temp[202];
            int y;
            temp[0] = string[index];
            strcat(temp,string); //gives me buffer overflow, any solution to this?
            //for(y = 0; y < (length); y++){  //my failed loop
                //temp[y+1] = string[y];
            //}
            int ind = length - index - 1;
            revstring[length] = revstring[ind];
            memcpy(string,temp,202);
        }
    }
    return 0;
}

There are lots of issues with your code. I'll just address your question about the buffer overflow (seg fault).

from man strcat:

The strcat() function appends the src string to the dest string, overwriting the terminating null byte ('\\0') at the end of dest, and then adds a terminating null byte.

But you don't have a terminating null byte at the end of dest. To fix the immediate problem:

temp[0] = string[index];
temp[1] = 0;

What else should I mention?

from man gets:

Bugs: Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.

Learn about null terminated strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM