1

I'm working on an assignment, but I'm having trouble with my code :

int is_ascii_match(const char c1[], const char c2[], char res[MAX_STRING_SIZE]) {
....

    if (val_c1 == val_c2) {
        strcpy(res, strcat(strcat(c1, '&'),c2));
    }
    else
        return 0;

I'm getting an error :

Access violation reading location

Do I pass the parameters wrong or..?

sagi
  • 40,026
  • 6
  • 59
  • 84
  • Are the calculation and values of `val_c1` and `val_c2` relevant to your question? If no, why include these lines? If yes, what are they? – Jongware Dec 05 '17 at 14:50
  • I find it difficult to believe that a user of your reputation doesn't know about [minimal complete examples](https://stackoverflow.com/help/mcve). – Beta Dec 05 '17 at 14:54
  • That's because I assumed the error has something to do with the arrguments I pass in the String functions, and it doesn't seems like any other info is neccesary @Beta , Still new to C though, so maybe I'm wrong . – sagi Dec 05 '17 at 15:20
  • 1
    Don't ignore compiler's diagnostic messages. The compiler, I'm sure, informed you about the problem. – AnT stands with Russia Dec 05 '17 at 15:43

2 Answers2

2

strcat expects a non-const char*. You passed a const that's why compiler complained.

Also the second parameter would be "&". (Earlier you passed a char).

From standard §7.24.3.1

char *strcat(char * restrict s1, const char * restrict s2);

The strcat function appends a copy of the string pointed to by s2 (including the terminating null character) to the end of the string pointed to by s1.

So s1 will be modified (the first parameter) that's why it should be non-const.

user2736738
  • 30,591
  • 5
  • 42
  • 56
0

'&' is a character literal, which is a small integer. The second argument of strcat is a const char*, which is a pointer to a character (more precisely, a pointer to the first character in a contiguous NUL-terminated array of chars). You presumably intended "&", which is a two-byte array.

Attempting to interpret a small integer as a pointer leads to precisely the problem indicated by the error.

If it were not for the problem reading the second argument, you might be presented with an error when strcat attempts to modify the string pointed to by its first argument, which is const and thus conceivably in read-only memory. (Modifying the first argument seems semantically incorrect, as well.)

If you compile with warnings enabled, you should see a warning about the types of the argument.

For this particular problem, consider the use of snprintf(res, MAX_STRING_SIZE, "%s&%s", c1, c2), which avoids modifying c1 and protects against buffer overflow. (You should compare the return value with MAX_STRING_SIZE if you care about truncation.)

rici
  • 234,347
  • 28
  • 237
  • 341