cpointersprintfdynamic-memory-allocation

error: passing argument 1 to restrict-qualified parameter aliases with argument 3 [-Werror=restrict]


When I manually test my program it compiles and works fine but when I try to use the autograder in the terminal I get this error. I am new to C and do not understand what it means and how to fix it.

My code:

#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<stdlib.h>
int main(int argc, char* argv[]){
    
    char *s = (char *)malloc(sizeof(char) * 100);
    char prev = argv[1][0];
    if(isdigit(prev)!=0){
        printf("%s","ERROR");
        return 0;
    }
    
    int count = 1;
    for(int i=1; i<strlen(argv[1]); i++){
        if(isdigit(argv[1][i])!=0){
            printf("%s","ERROR");
            return 0;
        }
        if(prev==argv[1][i]){
            count++;
        }else{
            sprintf(s, "%s%c%d", s, prev, count);
            count = 1;
        }
        prev=argv[1][i];
    }
    sprintf(s, "%s%c%d", s, prev, count);
    if(strlen(s) > strlen(argv[1])){
        printf("%s\n", argv[1]);
    }else{
        printf("%s\n", s);
    }
    free(s);
      
}

Solution

  • You're not allowed to sprintf a string to itself. That is, you can't pass the string s as one of the source arguments to sprintf when s is also the destination.

    See Is sprintf(buffer, "%s […]", buffer, […]) safe?. Also cppreference, under Notes:

    The C standard and POSIX specify that the behavior of sprintf and its variants is undefined when an argument overlaps with the destination buffer. Example:

        sprintf(dst, "%s and %s", dst, t); // <- broken: undefined behavior
    

    You'll need to come up with a different way to concatenate the desired characters and numbers together.