c - 为什么内存不分配?

标签 c arrays memory malloc word

我的任务是允许用户输入任何内容并打印出现的字母和单词。我们还必须打印出字符串中有多少个字母、两个、三个等字母单词。

在处理指针数组时,字函数存在访问冲突。看起来 malloc() 函数没有正确地为我的指针数组分配内存,我不确定我的编码是否正确。

我实际上尝试将内存分配给数组的索引 word[0],并且该索引具有正确分配的内存,但是当我使用循环时它永远不会工作,当我悬停时在数组上检查每个索引,它显示“Bad PTR”。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


void findLetters(char *ptr);
void findWords(char *point);


int main()
{
    char textStream[100]; //up to 98 characters and '\n\ and '\0'

    printf("enter some text\n");
    if (fgets(textStream, sizeof (textStream), stdin)) //input up to 99 characters
    {
        findLetters(textStream);
        findWords(textStream);
    }
    else
    {
        printf("fgets failed\n");
    }

    return 0;
}

void findLetters(char *ptr) //find occurences of all letters
{ /*Works fine*/ }

void findWords(char *point)
{
    int i = 0;
    int k = 0;
    int count = 0;
    int j = 0;
    int space = 0;
    int c = 0;
    char *word[50];
    char word1[50][100];
    char* delim = "{ } . , ( ) ";

    for (i = 0; i< sizeof(point); i++) //counts # of spaces between words
    {
        if ((point[i] == ' ') || (point[i] == ',') || (point[i] == '.'))
        {
            space++;
        }
    }
    char *words = strtok(point, delim);
    for(;k <= space; k++)
    {
        word[k] = malloc((words+1) * sizeof(*words));
    }

        while (words != NULL)
        {
            printf("%s\n",words);
            strcpy(words, word[j++]);
            words = strtok(NULL, delim);
        }

    free(words);
}

我的代码有什么问题?

最佳答案

 while (words != NULL)
 {
      printf("%s\n",words);
      strcpy(words, word[j++]);
      words = strtok(NULL, delim);
 }

free(words);

想想这段代码在做什么;它循环直到 words == NULL , 然后尝试 free (words) ,如果循环终止,则为 NULL .所以,你正在尝试 free一个NULL指针。

顺便说一句。你不需要释放 strtok的返回值:Do I need to free the strtok resulting string?

编辑:解决方案是这样的:

  1. for (i = 0; i< sizeof(point); i++)应该是 for (i = 0; i< strlen(point); i++) - sizeof(char*)不是字符串的长度, 而是系统上字符指针的大小(4 或 8)。
  2. 替换之后的所有内容 for上面的循环:

    char *words = strtok(point, delim);
    for (; k <= space && words != NULL; k++)
    {
        if (k >= 50)    //size of the word array
        {
            puts ("Too many words!");
            return;
        }      
    
        word[k] = malloc(strlen(words) + 1);
    
        strcpy(word[k], words);
        words = strtok(NULL, delim);
    }
    
    for (int i = 0; i < k; i++)
        free(word[i]);
    

该代码来自 Cool Guy 的回答,除了他那里有一个错误 - 代码递增 k两次。

请注意,这段代码实际上毫无意义,它只是分配一些内存,在那里复制一些东西,然后释放内存而不做任何事情,但我假设你想在 findWords 中做其他事情。之后的功能。

关于c - 为什么内存不分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30284171/

相关文章:

你能根据参数选择#define吗?

c# - 从数组中输入选择 C#

c - 将指针数组结构传递给函数

c - 我如何定义两个结构,每个都在第二个结构中使用? C语言

c - 使用 char 进行动态内存分配

c - ShowWindow() 是否发送 WM_SIZE 消息?

arrays - 快速逐列数组划分

C++ 对象 block 分配与单独分配

php - 定义大量常量会导致性能或内存问题吗?

c++ - Linux中多个进程使用文件指针读取文件时是否使用共享虚拟内存?