asaf
asaf

Reputation: 119

C Pointers & Memory - wrote a code...throw exception

so it will print: "aaa qqq ccc ddd bbb"

but from some reason that i don't understand it throw me exception. i wrote in the code where is the error. I know my code is a little messy so if you have also suggestion i will happy to hear.

Thank you!!!

void changeWords(char *s,int X, int Y)
{
    int len,words,i,count;
    len = count = words = i = 0;
    bool flag = false;
    while (s[len] != ' ')
        len++;
    char *p1 = (char*)malloc(sizeof(char)*(len+1));
if (p1== NULL)
{
    printf("Error: memory did not allocated");
    exit(1);
}
    char *p2 = (char*)malloc(sizeof(char)*(len+1));
if (p2== NULL)
{
    printf("Error: memory did not allocated");
    exit(1);
}
    while (flag == false)
    {
        if (count == (X-1))
        {
            for(int x = 0; x< len;x++,i++)
                p1[x] = s[i];
        }   
        else if (count == (Y-1))
        {
            for (int x = 0; x< len; x++,i++)
                p2[x] = s[i];
            flag = true;
        }
        if (s[i] == ' ')
            count++;
        i++;
    }
    p1[len] = p2[len] = '\0';
    i = count = 0;
    flag = false;
    while (flag == false)
    {
        if (count == (X-1))
        {
            for (int x = 0; x< len; x++, i++)
                s[i] = p1[x]; // here it throw an error "Unhandled exception thrown:.."
        }
        else if (count == (Y-1))
        {
            for (int x = 0; x< len; x++, i++)
                s[i] = p2[x];
            flag = true;
        }
        if (s[i] == ' ')
            count++;
        i++;
    }
    puts(s);
    free(p1); free(p2);
}
void main()
{
char*str = (char*)malloc(sizeof(char));
if (str == NULL)
{
    printf("Error: memory did not allocated");
    exit(1);
}
char ch;
int i = 0;
printf("Enter a string: ");
while ((ch = getchar()) != '\n')
{
    str[i] = ch;
    i++;
    str = realloc(str, sizeof(char) * (i + 1));
    if (str == NULL)
    {
        printf("Error: memory did not allocated");
        exit(1);
    }
}
str[i] = '\0';
func(str,3,5);
printf("new string: %s\n", str);

free(str);
system("pause");

}
}

Upvotes: 1

Views: 114

Answers (3)

rustyx
rustyx

Reputation: 85382

When you do this:

char * str = "aaa bbb ccc ddd qqq";

The string literal "aaa bbb ccc ddd qqq" is placed in the read-only data section, and str is made to point to it. At this point changing what str points to is undefined behavior and will hopefully raise a segfault.

If you absolutely want to use a pointer, try this instead:

char * str = strdup("aaa bbb ccc ddd qqq");

This will make a copy of the string literal on the heap, which will be writable.

Once you're done with it though you'll need to free(str); to release the memory.

Upvotes: 2

gsamaras
gsamaras

Reputation: 73376

Change this:

char * str = "aaa bbb ccc ddd qqq";

to this:

char str[] = "aaa bbb ccc ddd qqq";

since the first is a string literal.

String literals cannot be modified, thus your code invokes Undefined Behavior, in your function, where s is actually the string literal:

s[i] = p1[x];

PS: Unrelated to your problem: What should main() return in C and C++? int.


EDIT:

If you really want to use pointers, then you could create the array, and point with a pointer to its first element. Or, you could dynamically allocate memory for your string, which would be an overkill.

Upvotes: 1

Rafael Coelho
Rafael Coelho

Reputation: 166

  • the variable temp is not used
  • the length calculation is wrong. Use strlen from library string.h: int len = strlen(s)
  • I changed the main function too:

    int main() { char str[20] = "aaa bbb ccc ddd qqq";

    changeWords(str, 3, 5);
    printf("new string: %s\n", str);
    return 0;
    

    }

  • When i executed, it didn't make any exception. But you have logic issues. You have to find the words using ' ' to break the string. You could use strtok function too.

Upvotes: 0

Related Questions