简体   繁体   English

内存分配和动态内存分配

[英]memory allocation and dynamic memory allocation

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. 我是C编程的新手,我只是学习指针和字符串,我知道在使用指针和字符串时,我们必须为要使用动态内存分配声明的字符串分配内存。我想在不使用c函数库的情况下计算字符串的长度strlen()为什么下面的代码没有给出字符串的真实长度,而是当我将*string更改为string[50] ,这意味着我正在使用数组的方式进行计算,所以代码可以正常工作并给出实际长度的字符串。

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

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. 要计算长度,您需要一个分配了空间的指针,并分配需要计算长度的空间。

  1. 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. 在malloc()中,您传递的string是尚未初始化或尚未分配任何内存的指针,这意味着它包含一些垃圾值。 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. 然后,当您在len()计算其长度时,它会取消引用其中包含的垃圾地址, 令人惊讶的是,您在这里没有遇到段错误。

  2. And then you have not initialized len variable in your len() function, it just adds to the garbage value that len contains and returns. 然后您没有在len()函数中初始化len变量,它只是添加到len包含并返回的垃圾值中。

I ran your code and it gave me a segmentation fault because of the issues mentioned above. 我运行了您的代码,由于上面提到的问题,它给了我分段错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM