I wrote a program in ANSI C to remove the double quote in front and in the end of a string, so "Hello, world" would become Hello, world:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* removeQuotes(char str[]) {
int i = 1;
int len = strlen(str) - 2;
char * tmp = (char*) malloc (sizeof(char) * len);
for (;i<=len;++i ) {
tmp[i-1] = str[i];
}
return tmp;
}
int main(void) {
char str[] = "Hello, world";
char * abc = removeQuotes(str);
printf("Inside the quotes is: %s length: %d\n"
"Original is: %s length: %d", abc, strlen(abc), str, strlen(str));
return 0;
}
In IDEOne (http://ideone.com/Iybuk) I get the correct answer. But GCC gives me something weird:
U→┬↓ length: 22es is: ello, worlESSOR_↑
Original is: Hello, world length: 12
It happens only when the string contains a space. It works fine with “Helloworld” or something like that.
Any robust method to get it work correctly?
You have not allocated enough space for the null terminator.
You don’t add the null terminator to the end of your result.
Your source string doesn’t actually contain quotes.