0

I wrote an algorithm to extract words from a string and store them in an array,however i am getting an unwanted result and I can't figure out why.The output is being a very weird characters.

#include <stdio.h>
#include <windows.h>

char *extract(char *String)
{
char str[10][20];
int x = -1,y = 0,z = 0;
for( size_t n = 0 ; n < strlen(String) ; n++ )
{
    y++;
    if( String[n] == ' ' ) y = 0, z = 0;

    if( y == 1 ) x++;

    if( y > 0 )
    {
        str[x][z] = String[n];
        z++;
        str[x][z] = '\0'; //Comment this*********
    }
}

/*for( int n = 0; n < 10; n++ ) Uncomment this*****
{
    str[n][3] = '\0';
}*/

    return str[7];
}

int main()
{
    printf( "WORD : %s\n",extract("POL POL POL POL POL POL POL POL POL POL") );
    system("PAUSE");
    return 0;
}

where is the bug in this code?

Note: i also get weird characters when i use printf and strlen somewhere else.

Natasha Dutta
  • 3,242
  • 21
  • 23
machine_1
  • 4,266
  • 2
  • 21
  • 42

1 Answers1

7

The problem as I can see here, str is a local variable to the function extract() and you're trying to return it's address, and use that returned value as an argument to printf(). It invokes UB.

To clarify, str will exist until extract() finishes execution. Once it finishes ith execution and returns to the caller, there won't be any existence of str. So, the returned pointer will point to an invalid memory location. Using that retrun value further will lead to undefined behaviour.

Natasha Dutta
  • 3,242
  • 21
  • 23
  • Here's a working example without UB that copies the result into an output buffer: http://ideone.com/54aZh0 – AndyG Jul 02 '15 at 14:40