Question

Hello I try to read a string from main and then parse it to a function and find its size but my code doesn't works can you help me?

 //main
         int size=10;
            char *string= (char*) malloc (sizeof(char)*15);

            scanf("%s",string);
            findAllReplacements(NULL,10,string);

//at findAllReplacements

void findAllReplacements(nameInfoT* names,int size,char* expression){
    int ssize=strlen(expression);
    printf("%stringsize:%d\n",ssize);

The program crashes at strlen. What am I doing wrong? I give as input "astring"

The size argument has nothing to do with the size of the string;

Was it helpful?

Solution

The program crashes at strlen.

Possibly because the string that you enter from stdin is larger than the size of the allocated memory.

Few more issues

printf("%stringsize:%d\n",ssize);

Aparently, %s is interpreted as if, you would be passing a string as a vararg. So per your format string, your printf excepts two arguments of type string and integer consecutively, , but instead ended up passing a singleton integer. You should have coded as

printf("%%stringsize:%d\n",ssize);

In C, casting the return value of malloc is superfluous.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top