字符串指针意外更改其值 [英] Pointer to string changes its value unexpectedly

查看:63
本文介绍了字符串指针意外更改其值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,当在分配有malloc()的数组中写入字符串时,其值会改变.要清楚,这是复制此错误"的代码:

I have noted that, when writing a string in an array allocated with malloc(), its value changes. To be clear, here is the code that replicates this "error":

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

#define N (20)

int main()
{
   char * a_p;
   a_p = malloc( N * sizeof(char));
   printf(" * 01 pointer -> %p\n", a_p);
   a_p = "something";
   printf(" * 02 pointer -> %p\n", a_p);
   printf("-- TEST --\n");
   return 0;

}

执行时,输出为:

 * 01 pointer -> 0x1332010
 * 02 pointer -> 0x4006b9
-- TEST --

虽然我期望相同的值,因为我没有更改指针指向的位置(至少不是直接更改).使用free()时,这会导致问题.林下发生了什么?我想念什么?如何正确地做这些事情?

While I was expecting the same value because I am not changing where the pointer points (at least not directly). This causes problem when using free(). What is happening under the wood? What am I missing? How to do these things the right way?

推荐答案

您的问题

您正在使用malloc()为指针分配内存,但是随后将指针变量分配给其他变量("something",它具有自己的地址),而不是填充新分配的指针.

Your problem

You are allocating memory for your pointer with malloc() but then you assign your pointer variable to something else ("something", which has its own address), instead of filling the newly-allocated pointer.

您应该使用strdup()函数来分配内存,并在分配的内存中复制一个字符串:

You should use the strdup() function that allocates memory and copies a string at the allocated memory:

a_p = strdup("something");

strcpy()函数,该函数需要一个malloc()指针和一个要复制到指向内存中的字符串:

Or the strcpy() function, that takes a malloc()'d pointer and a string to copy in the pointed memory:

a_p = malloc(N * sizeof(char));
strcpy(a_p, "something");

这篇关于字符串指针意外更改其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆