Home > other >  Program output changes when ran in vim editor in windows
Program output changes when ran in vim editor in windows

Time:02-23

The program below is return in C. I have no idea why the output is changing when the program is same but the editor is different.

#include<stdio.h>
#include<stdlib.h>
struct Queue{
    int tail,head,capacity,size;
    int* array;
};

struct Queue* create_queue(int capacity){
    struct Queue *queue = (struct Queue*)malloc(sizeof(struct Queue*));
    queue->capacity = capacity;
    queue->head = 0;
    queue->tail = 0;
    queue->size = 0;
    queue->array = (int*)malloc(capacity * sizeof(int));
    return queue;
}

int isFull(struct Queue* q){
    return q->size == q->capacity;
}

int isEmpty(struct Queue* q){
    return q->size == 0;
}

void enqueue(struct Queue* q,int data){
    if (isFull(q)){
        return;
    }
    else{
        q->array[q->tail  ] = data;
        q->size = q->size   1;
    }
}

int dequeue(struct Queue* q){
    if (isEmpty(q) || (q->tail == q->head) || q->tail < q->head){
        return -1;
    }
    else{
        return q->array[q->head  ];
    }
}

int main(){
    struct Queue *qptr = create_queue(100);
    printf("Queue of capacity %d is created.\n",qptr->capacity);\
    enqueue(qptr,20);
    enqueue(qptr,30);
    enqueue(qptr,40);
    printf("The dequeued element is: %d\n",dequeue(qptr));
    return 0;
}

Below is the key mapping to build and to run a C file in Vim for your reference. Is there any need to change this mapping , I would like to know if any.

autocmd filetype c nnoremap <F2> :w <CR> :!gcc % -o %:r -Wl,--stack,268435456<CR>
autocmd filetype c nnoremap <F3> :!%:r<CR>

Vim output:

Queue of capacity -499734755 is created.
shell returned -1073741819

Codeblocks output:

Queue of capacity 100 is created.
The dequeued element is: 20

How can I fix this?

CodePudding user response:

(struct Queue*)malloc(sizeof(struct Queue*)); is fishy. I doubt the second *.

The idiom would be struct Queue *queue = malloc(sizeof(*queue));.
I.e. no casting and no repeating of datatype. What you malloc is too small, which means that your code is accessing beyond legally allocated memory.
You are only "lucky" (or unlucky, depening on whether you like hidden errors or not), that this undefined behaviour only causes different output in different environments.

  • Related