简体   繁体   中英

C stack smashing detected in array

I am trying to solve a question.

If in array a number is duplicated I make him 0. My code is throwing an error could you please help me?

#include <stdio.h>

int main() {
int a[] = {-3, -2, -1, -7, -3, 2, 3, 4, 2, 7, 10, 3}; 
int length = 12; 

int zero_duplicates(int laenge, int *a) {
    int zero[] = {};
    int k = 0;
    int j = 1;

    for(int x=0; x<laenge; x++)
    {
        if (zero[*a] == 1) {
            *a = 0;
        } else {
            zero[*a] = 1;
            k++;
        }
        a++;
    }
return k;
}


int count = zero_duplicates(length, a); 


printf("%d -- ", count); 

for(int i = 0; i < length; i++) printf(" %i ", a[i]);

return 0;
}

This...

 int zero[] = {};

... is not a valid array declaration in C. If your compiler accepts it as an extension then it ought at least to be emitting a warning, and even then it probably doesn't mean what you think it means. Specifically, among the most likely extensions would be to interpret that as declaring a zero-length array (which also would constitute an extension), such that accessing any element overruns the array bounds.

Moreover, no matter how long the array is, if any of the elements of the input array are negative (as is the case in the example) then zero[*a] will constitute an out-of-bounds access when a points to one of those elements.

Overall, you need a different approach. What you're trying to do is not viable.

As a separate matter, C does not support nested functions, so your code is relying on yet another extension in that respect. This particular issue can be resolved by lifting the nested function out of main() , however, putting it above instead of inside.

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