相关疑难解决方法(0)

free和malloc如何在C中工作?

我试图找出如果我试图从中间"释放"指针会发生什么,请看下面的代码:

char *ptr = (char*)malloc(10*sizeof(char));

for (char i=0 ; i<10 ; ++i)
{
    ptr[i] = i+10;
}
++ptr;
++ptr;
++ptr;
++ptr;
free(ptr);
Run Code Online (Sandbox Code Playgroud)

我收到一个崩溃,出现未处理的异常错误消息.我想了解为什么以及如何免费工作,这样我不仅知道如何使用它,而且还能够理解奇怪的错误和异常并更好地调试我的代码ץ

非常感谢

c memory malloc free

58
推荐指数
6
解决办法
7万
查看次数

为什么malloc分配的字节数与请求的数不同?

我有这段代码

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

int main(){
    void *a, *b;

    a = malloc(16);
    b = malloc(16);
    printf("\n   block size (for a): %p-%p : %li", b, a, b-a);

    a = malloc(1024);
    b = malloc(1024);
    printf("\n   block size (for a): %p-%p : %li", b, a, b-a);  
}
Run Code Online (Sandbox Code Playgroud)

这不应该打印最后分配的块大小(16或1024)?它改为打印24和1032,因此分配的内存量似乎有8个额外的字节.

我的问题是(在进行此测试用例之前)我malloc()在一个函数(1024字节)中执行,并返回分配的结果.在函数返回时检查块大小时,我得到了516个块......我不明白为什么.我想这可能是在对分配的缓冲区进行一些处理后发生内存损坏的原因:)

编辑:我已经看过如何从C中的指针获取数组的大小?似乎问了同样的事情,抱歉转发.

我已经将我的示例重新编写为更具体的代码:

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

short int * mallocStuff(long int number, short int base){
    short int *array;
    int size=1024; …
Run Code Online (Sandbox Code Playgroud)

c debugging malloc gcc

7
推荐指数
5
解决办法
2万
查看次数

argc/argv 随机数据/行为

这是我的最小可重现示例:

#include <stdio.h>

int main( int argc, char* argv[])
{
    printf (" this is the contents of argc:%d\n",argc);
            
    int i;

    for (i = 0; i < argc ; i++){
       printf(" argv = %d = %s\n",i,argv[i]);
    }
      
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我argc将 for 循环更改为数字时,比方说10,代码在到达之前崩溃10

$ ./argc one two three
 this is the contents of argc:4
 argv = 0 = ./argc
 argv = 1 = one
 argv = 2 = two
 argv = 3 = three
 argv …
Run Code Online (Sandbox Code Playgroud)

c argv argc

2
推荐指数
1
解决办法
159
查看次数

标签 统计

c ×3

malloc ×2

argc ×1

argv ×1

debugging ×1

free ×1

gcc ×1

memory ×1