您的位置:首页 > 运维架构 > Linux

Linux下C语言环境编程(gdb调试指针)

2018-03-13 20:42 369 查看
1.vim:



2.gcc:



3.预处理:



4.链接:



5.gdb调试



#include <stdio.h>
void swap(int a, int b)
{
int c;
c = a;
a = b;
b = c;
}

int main(void)
{
int a = 20;
int b = 30;

swap (a, b);
printf("a=%d  b=%d\n", a, b);
}

这是在swap函数中a,b的地址             这是在main函数中a,b的地址明显不一样,证明两个a,b是不一样的。所以a,b的值没有改变。还可以验证栈区地址是从上往下增长         全局变量g_argv的地址相对来说就小很多                                                                                                            




                  


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

void get_memory(char *ptr, int size)
{
ptr = malloc(size);
}

int main(void)
{
char *ptr = NULL;
get_memory(ptr, 100);

strncpy(ptr, "hello", 100);
printf("ptr: %s\n", ptr);

free(ptr);
return 0;
}

指针错误,内存错误,逻辑错误。


                                                                          

调试







两个ptr的地址空间不同,从下图也可以看出,ptr在函数中是0x0,说明这两个ptr是不同的



修改后的代码:

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

void get_memory(char **ptr, int size)
{
*ptr = malloc(size);
printf(":\n");
}

int main(void)
{
char *ptr = NULL;
get_memory(&ptr, 100);

strncpy(ptr, "hello", 100);
printf("ptr: %s\n", ptr);

free(ptr);
return 0;
}




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: