Community
Participate
Working Groups
Build Identifier: M20090917-0800 In C the life span of a variable in a function should only last till the end of the function but that is not happening in eclipse CDT. For example if I have a value returning function like this one: newString = stringToUpCase(usrString); stringToUpCase returns a pointer to char then if you haven't allocated memory to keep the contents of the pointer to char then it is suppose to return garbage but that is not happening. Here's an example with my code: #include <stdio.h> #include <string.h> #include <stddef.h> #define STRING_LENGTH 71 void getString(char *); char *stringToUpCase(char *); int main(void) { char usrString[STRING_LENGTH]; char * newString; getString(usrString); newString = stringToUpCase(usrString); printf("This is the Upper-Case string: %s\n", newString); getchar(); return 0; } void getString(char * usrString) { char tempString[STRING_LENGTH]; printf("Enter any type of string: "); fflush(stdout); gets(tempString); strcpy(usrString, tempString); } char *stringToUpCase(char * aString) { int i , strLen = strlen(aString); char charArray[STRING_LENGTH]; for(i = 0; i < strLen; i++) { if(*(aString +i) >= 'a' && *(aString +i) <= 'z') charArray[i] = (*(aString + i)) - 32; } charArray[strLen] = '\0'; return charArray; } here is picture of what I mean: http://i553.photobucket.com/albums/jj362/cabbae/error.jpg now the correct way to keep the contents of charArray is to allocate memory. Heres an example: char *stringToUpCase(char * aString) { int i , strLen = strlen(aString); char *charPtr = NULL; charPtr = malloc(strLen * sizeof(char)); for(i = 0; i < strLen; i++) { if(*(aString +i) >= 'a' && *(aString +i) <= 'z') charPtr[i] = (*(aString + i)) - 32; } charPtr[strLen] = '\0'; return charPtr; } Reproducible: Always
It's not clear what you think the problem with _cdt_ is here. What you've described is a peculiarity of the code produced by the compiler happening to work -- the array is on the stack so was valid st some point in time. A tool like valgrind will tell you about the bug... Nothing to do with eclipse afaics.
What I'm trying to say is that if I create a static variable at a function level, that variables life span should only be the duration of the function. So if I were to lets try an access that variable from outside the function it should contain garbage and not the original contents it had but that's not the case. I still have the original contents intact.
Would valgrind help me find the error?
No because this is C Standard. This is definition of static variable. If you mean "auto" - which is stack variable - its life span it function only, and it may or may not contain garbage after you exit. Implementation specific. Read the standard.