Question :
I am trying to do an exercise that tests if there is some blank before a string and removes it if it does, however it is returning the following error:
Targeting failure (recorded core image)
I can not understand why.
Code:
#include <stdio.h>
void removerEspacosEsquerda(char string[]) {
int i, j, cont;
char *string2, a;
i = 0;
cont = 0;
while(string[i] != 0) {
if(string[i] == ' ') {
cont++;
}
i++;
}
i = 0;
j = 0;
printf("%d", cont);
while(string[i] != 0) {
if(i >= cont) {
string2[j] = string[i];
}
i++;
j++;
}
string = string2;
}
int main() {
char *string;
string = " teste";
removerEspacosEsquerda(string);
printf("%s", string);
}
Answer :
Your code is too complex and the error occurred because of this, when we simplify the error and have no opportunity to appear. You do not need 2 loops (3 for the solution of the other answer) and you do not need to allocate memory:
#include <stdio.h> void removerEspacosEsquerda(char string[]) { int cont = 0; for (int i = 0; string[i] != '
#include <stdio.h> void removerEspacosEsquerda(char string[]) { int cont = 0; for (int i = 0; string[i] != '%pre%'; i++, cont++) { if (string[i] == ' ') cont--; else string[cont] = string[i]; } string[cont] = '%pre%'; } int main() { char string[] = " teste"; removerEspacosEsquerda(string); printf("%s", string); }
'; i++, cont++) {
if (string[i] == ' ') cont--;
else string[cont] = string[i];
}
string[cont] = '%pre%';
}int main() {
char string[] = " teste";
removerEspacosEsquerda(string);
printf("%s", string);
}
See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .
The segmentation fault occurs because the string2 pointer has not been initialized.
#include <stdio.h>
#include <stdlib.h> // para malloc e free
void removerEspacosEsquerda(char string[])
{
int i, j, cont;
char *string2 = malloc(strlen(string)+1), a; // <-------------
i = 0;
....
....
strcpy(string, string2);
free(string2); // <-------------
} // fim removerEspacosEsquerda
Note that I have not looked at whether your space-saving logic is correct, I’m just solving the problem of segmentation failure.