This is my code:
#include <stdio.h>
#include <stdlib.h>
void getinfo(unsigned int a, unsigned int b, char **s);
int main(){
unsigned int len_max = 8;
unsigned int current_size = 0;
char *pStr = malloc(len_max);
if(pStr == NULL){
perror("\nMemory allocation\n");
return EXIT_FAILURE;
}
current_size = len_max;
printf("Inserisci hostname: ");
getinfo(len_max, current_size, &pStr);
printf("\nLa stringa inserita è: %s\n", pStr);
free(pStr);
return EXIT_SUCCESS;
}
void getinfo(unsigned int a, unsigned int b, char **pStr){
unsigned int i = 0;
char c = EOF;
while((c = getchar()) != '\n'){
*pStr[i++] = (char)c;
if(i == b){
b = i+a;
if((*pStr = realloc(*pStr, b)) == NULL){
perror("\nMemory allocation error\n");
exit(EXIT_FAILURE);
}
}
}
*pStr[i]='\0';
}
When i execute this code i got a segmentation fault when i press enter (after i’ve wrote the string).
I’m sure the problem is into the function (probably the problem is the *s pointer) but i don’t know how to correct it…
You have a precedence problem. You need to use
instead of
Similarly you need
When you write
*s[i]you are indexings. But you want to index*s, and hence require the parentheses.I’ve not checked the rest of your code, but I hope this helps you on your way to debugging the rest of it, if indeed there are more errors.