i just startet to coding in c, and dont have a big background.
now i have a problem witch i dont understand. i hope you guys can help me out here.
the problem is malloc. i try to allocate space for a padded string.i get the lenght of the new string with strlen and then try to allocate space with that value.but this does not work.the buffer had the size of 16 instead of 8, or 24 instead of 16 and so on.
this is my code:
Expand|Select|Wrap|Line Numbers
- int tfis()
- {
- ERRCODES Status = 0;
- int I;
- const char PaddingByte = 0x24; //dollar sign
- char TestString[30] = "AAAAXAAA";
- int StringLength = strlen(TestString);
- unsigned int StringLengthNew;
- unsigned short int TheCounter = 0;
- char C;
- unsigned char *StringTable = 0;
- for(I=0; I<=StringLength; I++)
- {
- C = TestString[i];
- if(! (C == 0))
- {
- printf("%c", C);
- }
- else
- {
- printf(" End of File..\n");
- if((I%8 == 0)&&(I != 0))
- {
- //add at least 8 bytes..
- printf("1. the string had a length of %d bytes\n", I );
- printf("1. padding not needed, add at least 8 bytes\n");
- do
- {
- TestString[i] = PaddingByte;
- printf("%s\n", TestString);
- I++;
- TheCounter++;
- }while(I%8 != 0);
- }
- else
- {
- //add ++ bytes
- printf("2. the string had a length of %d bytes\n", I);
- printf("2. padding needed, add ++ bytes\n");
- do
- {
- TestString[i] = PaddingByte;
- printf("%s\n", TestString);
- I++;
- TheCounter++;
- }while(I%8 != 0);
- }
- }
- }
- StringLengthNew = strlen(TestString);
- printf("the new string has a length of %d bytes. the value: %s\n", StringLengthNew, TestString);
- printf("%d bytes added..\n", TheCounter);
- TheCounter = 0;
- StringTable = malloc(StringLengthNew); //allocate space for the new output buffer
- printf("output size: %d\n", strlen(StringTable));
- if(! StringTable)
- {
- printf("error..\n");
- Status = BUFFER_SIZE;
- return Status;
- }
- else
- {
- printf("success..\n");
- strncpy(StringTable, TestString, StringLengthNew); //copy the value to the new buffer
- printf("Output String: %s\n", StringTable);
- }
- free(StringTable);
- StringTable = 0xc;
- return Status;
- }