jBannon
jBannon

Reputation: 9

Strange Struct Array Printing Error in C

Hey all I'm having some trouble diagnosing the reason for an error in printing an array of structures in C.

In a separate header file (call it header.h) I have the following typedef'd structure:

typedef struct instruction prog;

struct instruction{
char kind;
char op[4];
};

For my main programing task I want to read from a file a series of what are supposed to be instructions consisting of a type character (the variable kind above) and an instruction consisting of four integers (listed as op above). Examples include R 1004 E 1008, etc. I can read the data in just fine but it seems to be storing things improperly. I wrote the following test code to see if I could find the error but I was still getting the same issue. My goal is to store these as an array of instructions where, using the parlance of the code below, mem[i].kind = 'R' and mem[i].op =1004`.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
#include "header.h"

void memFill(prog *P, int x);
void memPrint(prog *P, int x);

int main(){
    prog mem[10];

    memFill(&mem[0], 10);
    memPrint(&mem[0], 10);
return 0;
}


void memFill(prog *P, int x){
char *v = "1004";
for(int i = 0; i< x; i++){
    P->kind = 'R';
    strcpy(P->op, v);
    P++;
}
}


void memPrint(prog *P, int x){
for(int i = 0; i <x; i++){
    printf("%c %s\n",P->kind, P->op);
    P++;
}
}

This is giving me output that looks like this:

R 1004R1004R1004R1004R1004R1004R1004R1004R1004R1004
R 1004R1004R1004R1004R1004R1004R1004R1004R1004
R 1004R1004R1004R1004R1004R1004R1004R1004
R 1004R1004R1004R1004R1004R1004R1004
R 1004R1004R1004R1004R1004R1004
R 1004R1004R1004R1004R1004
R 1004R1004R1004R1004
R 1004R1004R1004
R 1004R1004
R 1004

The reason this is weird is that identical pointer arithmetic has given just fine results with a similar structure. What's going on here? What am I missing?

Upvotes: 0

Views: 185

Answers (2)

Frankie_C
Frankie_C

Reputation: 4877

You forgot to give space for the string ending null. Fix your struct declaration to this:

struct instruction{
char kind;
char op[5];
};

And it will work.
You can also simplify declaration this way:

typedef struct instruction{
char kind;
char op[5];
} prog;

Upvotes: 0

LPs
LPs

Reputation: 16223

Buffer overflow on char op[4], then Undefined_behavior

To be able to store "1004" it have to be 5 bytes long to have space for NULL terminator.

struct instruction{
char kind;
char op[5];
};

Literal string "1004" is '1', '0', '0', '4', '\0'

Upvotes: 1

Related Questions