简体   繁体   中英

C language, char array is corrupted(?)

I don't do anything to 'org' char array, but when I see the output. 'org' array is changed from banana to bana. I guess this is caused by memory corruption or something, but I don't know what is wrong exactly. How can I fix the contents of org char array?

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

char org[];
int N;
char clue[1010][110];
int arrest[1010];

void solve(){ // Core function
    char* copy;
    int len_org, len_clue, tmp=0, cnt=0;
    int i, j;

    len_org = strlen(org);
    //printf("len_org = %d\n", len_org);

    for(i=0; i<N; i++){
        //copy = org;
        //memset(copy, 0, strlen(len_org));
        //printf("org = %s\n", org);
        copy = org;
        cnt = 0;
        printf("first copy = %s, org = %s\n", copy, org);
        len_clue = strlen(clue[i]);
        printf("len_clue = %d\n", len_clue);
        tmp = len_org - len_clue;
        for(j=0; j<=tmp; j++){
            printf("clue[i] = %s, copy = %s\n", clue[i], copy);
            if(!strncmp(copy, clue[i], len_clue)){
                cnt++;
                printf("cnt = %d\n", cnt);
            }
            copy++;
            printf("copy = %s, org = %s\n", copy, org);
        }
        printf("final cnt = %d\n\n", cnt);
        arrest[i] = cnt;
    }

    /*for(i=0; i<N; i++)
        printf("%s\n", clue[i]);*/
}

void inputData(){
    int i;
    scanf("%s", org);
    scanf("%d", &N);
    for(i=0; i<N; i++){
        scanf("%s", clue[i]);
    }
}

int main() {
    inputData();
    solve();
    return 0;
}

Compiling the code with gcc (7.3) identify the problem:

cc a.c
a.c:4:6: warning: array ‘org1’ assumed to have one element
 char org1[];
      ^~~~

In practice (gcc 7.3) The 'org' is placed between 'clue' and 'arrset' (global) variables. As can be seen from 'nm a.out' - the arrest start 4 bytes after org, making the effective size of 'org' to be 4.

Output from: nm a.out | sort

0000000000201040 B N
0000000000201060 B clue
000000000021c25c B org
000000000021c260 B arrest
000000000021d228 B _end

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