I'm having a problem returning a string from a function. I'm writing some code in C using Visual Studio 2022 that handles characters, but if the characters are control codes, I want to return the official names such as "NUL", "ESC" etc., rather than printing out the control characters themselves, which can produce spurious output, and in the case of a line feed mess up the printed output.
A much simplified version of the main function is as follows:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
typedef unsigned char BYTE;
void showASCIIContrChars(const char, char[]);
int main(void) {
int numEls = 500;
char conChars[4] = { '\0', '\0','\0', '\0' };
BYTE* bufA = calloc(numEls, 1);
for (int i = 0; i < 500; i++) {
bufA[i] = i;
showASCIIContrChars(bufA[i], conChars);
printf("%3d %s\n", i, conChars);
}
}
The function called from main is as follows:
void showASCIIContrChars(const char c, char str[]) {
static bool first = true;
static char** contrs = NULL;
if (first) {
char *contrs[35] = { "NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL",
"BS ", "HT ", "LF ", "VT ", "FF ", "CR ", "SO ", "SI ",
"DEL", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB",
"CAN", "EM ", "SUB", "ESC", "FS ", "GS ", "RS ", "US ",
"SPA", "DEL", "INV"};
first = false;
}
if (c < 0 || c > 127) {
strcpy_s(str, 4, contrs[34]);
} else if (c < 33) {
strcpy_s(str, 4, contrs[c]); // <===
} else if (c == 127) {
strcpy_s(str, 4, contrs[33]);
} else {
str[0] = c;
str[1] = ' ';
str[2] = ' ';
}
}
The actual code does rather more, but this is a simplified part of it.
What I want showASCIIContrChars() to do is to return a string with 2 or 3 characters for the control codes 0 to 31, and 127, and for convenience return "SPA" for a space. "I've also included "INV" for invalid for codes outside the range 0 to 127. For codes between 33 and 126, which are the normal printable characters other than a space (code 32), I just want to return that character. In all cases any trailing spaces in the returned string are padded if needed, and terminated by a NUL, '\0' character.
The code compiles without errors, but on attempting to run it, an exception is thrown at the line indicated by "<==" with an error message: .... 0x000000C: Access violation reading location 0x followed by a long strings of 0s. Unfortunately copy and paste doesn't work.
Incidentally I used typedef for an unsigned char as BYTE, but this should not have any effect. In many of my codes I use this so that all bytes have non-negative values, as in many cases the bytes do not represent characters, but the do here.
There must be a simple explanation for this error and fix it. I look forward to some help on this.
contrsinside the if statement?