This code runs in visual studio, but segmentation fault happens in programming site's compiler(C99, C11)
It seems like there is segmentation fault on strncpy, but I dont know how to fix this...
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int element;
element stack[30];
int top_pointer = -1;
int peek() {
return stack[top_pointer];
}
void push(int real_element) {
stack[++top_pointer] = real_element;
}
void pop() {
top_pointer = top_pointer - 1;
}
void about_push(char* enter) {
char* push_check = "push";
char* result_push;
result_push = strstr(enter, push_check);
while (result_push == NULL) {
return;
}
result_push = strstr(enter, " ");
int push_box = atoi(result_push);
push(push_box);
}
void about_pop(char* enter) {
char* pop_check = "pop";
char* result_pop;
result_pop = strstr(enter, pop_check);
while (result_pop == NULL) {
return;
}
pop();
}
void about_size(char* enter) {
char* size_check = "size";
char* result_size;
result_size = strstr(enter, size_check);
if (result_size == NULL) {
return;
}
printf("%d\n", top_pointer + 1);
}
void about_empty(char* enter) {
char* empty_check = "empty";
char* result_empty;
result_empty = strstr(enter, empty_check);
if (result_empty == NULL) {
return;
}
else if (top_pointer == -1) {
printf("1\n");
}
else {
printf("0\n");
}
}
void about_top(char* enter) {
char* top_check = "top";
char* result_top;
result_top = strstr(enter, top_check);
if (result_top == NULL) {
return;
}
else if (top_pointer == -1) {
printf("-1\n");
}
else {
printf("%d\n",stack[top_pointer]);
}
}
int main(void) {
int size;
printf("You can type number between 1 to 10000.\n");
scanf("%d", &size);
while (getchar() != '\n');
char** enter = (char**)malloc(sizeof(char*) * size);
for (int i = 0; i < size; i++) {
enter[i] = (char*)malloc(sizeof(char) * 10);
}
for (int i = 0; i <= size - 1; i++) {
scanf("%11[^\n]", enter[i]);
getchar();
}
for (int i = 0; i <= size - 1; i++) {
char* copy = (char*)malloc(sizeof(char)*10);
char* copy2 = (char*)malloc(sizeof(char) * 10);
char* copy3 = (char*)malloc(sizeof(char) * 10);
char* copy4 = (char*)malloc(sizeof(char) * 10);
int length = strlen(enter[i])+1;
strncpy(copy,enter[i],length);
strncpy(copy2,enter[i],length);
strncpy(copy3,enter[i],length);
strncpy(copy4,enter[i],length);
about_push(enter[i]);
about_pop(copy);
about_size(copy2);
about_empty(copy3);
about_top(copy4);
}
for (int i = 0; i <= size - 1; i++) {
free(enter[i]);
}
free(enter);
}