1
#include <stdio.h>   
struct Bar{
    int max;
    int N;
    int k[4];
    float g[4];
};


typedef struct Bar myStruct;



myStruct entr(){
    myStruct result;
    int i;

    printf("max\n");
    scanf("%d", &result.max);

    printf("N = \n");
    scanf("%d", &result.N);

    printf("\nEnter k = ");
    for(i=1; i<=4; i++) scanf("%d", &result.k[i]);

    printf("\ng = ");
    for(i=1; i<=4; i++) scanf("%f" , &result.g[i]);

    return result;
}


void main() {       
    myStruct entrs=entr();
}

I ran this code in linux (compile with gcc), and every time it has the following error

"* stack smashing detected *: ./a.out terminated Aborted "

How can I resolve this error?**

1 Answer 1

7

The problem is with the boundary (overrun).

In your case

  for(i=1; i<=4; i++)

should be

  for(i=0; i<4; i++)

as C arrays use 0-based indexing. Otherwise, with your code, you're

  • leaving the element at index 0 unused (lesser problem)
  • going off-by-one, accessing out of bound memory (bigger issue, causes undefined behavior.)

That said, void main() should be int main(void) for a hosted environment to be standard conforming.

Sign up to request clarification or add additional context in comments.

1 Comment

this is the right response. Nothing to add, well done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.