sagi
sagi

Reputation: 40491

C string functions error

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..?

Upvotes: 1

Views: 203

Answers (2)

rici
rici

Reputation: 241931

'&' 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.)

Upvotes: 0

user2736738
user2736738

Reputation: 30936

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.

Upvotes: 2

Related Questions