Reputation: 63
i am new in c programming and i just learn about pointer and string,i know when working with pointer and string we must allocate memory for string we want do declared using dynamic memory allocation.I want to calculate length of string without using c function library strlen()
.but why this below code doesn't give the real length of string,instead when i change *string
to string[50]
that means i am using array way to calculate,the code works fine and give me the real length of string.
this the code:
#include <stdio.h>
#include <stdlib.h>
int len(char *string);
int main(void){
char *string;
string=(char *)malloc(len(string+1));
puts("enter string:");
fgets(string,sizeof(string),stdin);
printf("length=%d\n",len(string));
return 0;
}
int len(char *string){
int len;
while(*string!='\0'){
string++;
len++;
}
return len-1;
}
this is when i run that code:
enter string:
programming
length=2
Upvotes: 0
Views: 109
Reputation: 11649
Your code describes the chicken and egg problem. To calculate the length, you need a pointer with allocated space & to allocate space you need to calculate the length.
In
string=(char *)malloc(len(string+1));
In malloc(), you are passing string
which is a pointer which hasn't yet been initialized or allocated any memory, meaning it contains some garbage value. And then when you calculate its length in len()
, it de-references the garbage address it contains, surprisingly you don't get a segfault here.
And then you have not initialized len
variable in your len()
function, it just adds to the garbage value that len
contains and returns.
I ran your code and it gave me a segmentation fault because of the issues mentioned above.
Upvotes: 3