简体   繁体   中英

Stack smashing error when manipulating array of ints in function

So I'm trying to make a simple program that takes an array that is partially full and adds an integer to the beginning shifting all existing elements to the right. It seems what I have here adds and shifts things properly but once all the code executes, I get a stack smashing detected error.

Here is my code:

#include <stdio.h>

void addCommand(int *, int, int);

void main() {
    int i;
    int list[10];
    list[0] = 1;
    list[1] = 5;

    printf("Before add:\n");
    for (i = 0; i < 2; i++) {
        printf("%d\n", list[i]);
    }

    addCommand(list, sizeof(list), 4);

    printf("Adding 4:\n");
    for (i = 0; i < 3; i++) {
        printf("%d\n", list[i]);
    }
}


void addCommand(int *arr, int size, int new) {
    int k;
    printf("%d", arr[0]);   
    for (k = size - 1; k >= 0; k--) {
         if (&arr[k] != NULL) {     
            if (k > 0) {        
                arr[k] = arr[k-1];
            } else {
                arr[k] = new;
            }
        }   
    }   
}

And here's the output:

在此处输入图片说明

If anyone could point out what I'm doing wrong here, it would be much appreciated!

addCommand(list, sizeof(list), 4);

above line doesn't pass number of element in list array. you have to do something like this:

sizeof(arr)/sizeof(arr[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