简体   繁体   中英

buffer overflow while writing to char array

Could anyone help me out here? I don't really know why this code doesn't work properly. Just want to split a string in two. However, somehow strange thing happen that it writes 6 char instead of 3 char . The for loop executes 3 times .


Code

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

int main(){
    char array[100] = "aaa-aaaaa";
    char first[100];
    char last[100];
    for(int i = 0; i < strlen(array); i++){
        if(array[i] == 45){
            for(int a = 0; a < i; a++){
                first[a] = array[a];
        }
        for(int a = 0; a < (strlen(array) - (i+1)); a++){
            last[a] = array[(a+i+1)];
        }

        }
    }
    printf("%s and the length is %d\n", first, strlen(first));
    for(int i = 0; i < strlen(first); i++){
        printf("%d ", first[i]);
    }

    printf("\n%s and the length is %d\n", last, strlen(first));
    for(int i = 0; i < strlen(last); i++){
        printf("%d ", last[i]);
    }
    return 0;
}

Output

aaa�� and the length is 6
97 97 97 -76 -1 127 
aaaaa and the length is 6
97 97 97 97 97 % 

After the first for is finished add this: first[a]='\\0'; strlen is calculated by iterating from the first element to \\0 .

unsigned int firstLen=0, secLen=0;
while(array[firstLen]!='-'){
    first[firstLen] = array[firstLen];
    firstLen++;
}
first[firstLen]='\0';
secLen=firstLen;
while(array[secLen]!='\0'){
    last[secLen-firstLen] = array[secLen];
    secLen++;
}
last[secLen-firstLen]='\0';

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