Results 1 to 2 of 2

Thread: Makes NO SENSE

  1. #1

    Thread Starter
    Member
    Join Date
    Apr 2008
    Posts
    42

    Makes NO SENSE

    I wrote this function.

    Code:
    char* GetExtension(char* cFile)
    {
        char* cExt = (char*)malloc(30);
    	 int i,x,z;
    	 for(i=0;i<strlen(cFile);i++){
    		 if(cFile[i] == '.'){
    			 for(x=i+1;x<strlen(cFile);x++){
    				cExt[z++] = cFile[x];
    			 }
    			 cExt[z++] = '\0';
    			 z++;
    		 }
    	 }
        return cExt;
    }
    I call it in main, it works fine.

    Code:
    char* pNoSense = GetExtension("***NOSENSE.txt");
    printf("NO SENSE: %s\n",pNoSense);
    free(pNoSense);
    return 0;

    I call it later again in my program and it doesn't seem to return any output. I started putting it in random places to see *** the problem is, and at some places it even crashes the damn thing. Help?

  2. #2
    Hyperactive Member pgag45's Avatar
    Join Date
    Mar 2007
    Location
    Colorado
    Posts
    262

    Re: Makes NO SENSE

    hmm..

    well it appears you are returning a pointer to a stack based (temporary variable)... you create cExt in the method then return the pointer.. but after exiting the method that stack based variable is deleted, so that pointer is pointing to garbage...

    use the keyword "new" to create a heap based variable or pass by reference.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width